0

I have code:

angular.module('admin', [])
.provider('users', function () {
  this.users = 'default';
  this.$get = function () {
    var that = this;
    return {
        getUsers: function () {
            return that.users;
        }
    }
};
})
.run(function (users, $http) {
  users.users = $http('url'); // and others
})
.controller('test', function ($scope, users) {
    $scope.users = users.getUsers();
});

I would like to intitalize data in .run() method (I can't use .config() method because it doesn't let to pass any services like $http). I found .run() method, but this code doesn't work... Data aren't saved in provider. Official documentation says:

"Execute this function after injector creation. Useful for application initialization."

I think it's best way to initialize data.

3 Answers 3

1

You may want to use an Angular Factory/Service for this kind of need. That is what I do. And pass that into the application. That service will be your singleton or source of truth about the dat.

angular.module('myData.services', [])
  .factory('myData', ['$rootScope', '$http' , function($rootScope,$http) {

            var factory = {
                myData : {}
            };
    
            $http('/api/call', function(apiData) {
              factory.myData = apiData;
            });

            return factory;
        }]);

You could then use this in your controllers:

angular.module('myApp.controllers', [])
    .controller('myCtrl', ['myData', '$scope', function(myData, $scope){
        $scope.users = myData;
    }]);

Check out the documentation on services: https://docs.angularjs.org/guide/services

Sign up to request clarification or add additional context in comments.

3 Comments

I know this solution. I thought that provider is the best solution, because it has a config() and run() methods, which should be good for initializing data.
Well the service initializes itself and you can keep all of the code in one place instead of having to manage that initialization somewhere else.
@TyMayn Are services that initialize themselves not bad?
0

Second attempt

angular.module('admin', [])
.factory('users', function ($http) {
  var users = {};
  var data = [];

  $http.get('database.php')
    .then(function (response) {
        data = response.data;
    });

  users.getData = function () {
  return data;
  };

  return users;
})
.controller('test', function ($scope, users) {
  console.log(users.getData());
});

I would like to have data private. Empty Array returned, reponse comes with all data.

Comments

0

Provider configuration can be doable inside config block only, you can't do that inside run block

Though I don't find a reason to load users object while configuring app. I'd say that you should use either service/factory for this.

Code

angular.module('admin', [])
.service('users', function($http, $q) {
  var users = [];
  //make an get call to fetch users
  function getUsers() {
    return $http.get('database.php')
      .then(function(response) {
      data = response.data;
    });
  }

  //will make a call if users aren't there
  this.getData = function() {
    // Handled below two conditions
    // 1. If users aren't fetched the do an Ajax
    // 2. If last ajax doesn't return a data then DO it again..
    if (users.length > 0)
      return $q.resolve(data); //do return data using dummy promise
    return getUsers();
  };
  return users;
})

.controller('test', function($scope, users) {
   users.getData().then(function(data){
      console.log(data);
   });
});

4 Comments

But in the config method i can't use any services like $http.
@Gary you can't have access to $http method while having $httpProvider object.. because they belongs to $get, and it doesn't instantiated yet..
@Mati hhonestly speaking, I don't see advantage on having users available in configuration time..
I want to have users loaded once. I thought that provider would be good option but if not i would like to have better way.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.