Mati
Mati

Reputation: 781

AngularJS Initialize provider data

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.

Upvotes: 0

Views: 1311

Answers (3)

Pankaj Parkar
Pankaj Parkar

Reputation: 136144

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);
   });
});

Upvotes: 0

Mati
Mati

Reputation: 781

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.

Upvotes: 0

TyMayn
TyMayn

Reputation: 1936

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

Upvotes: 1

Related Questions