Dribel
Dribel

Reputation: 495

Getting asynchronous data from service

I try to request some data in a service. I wanna make sure sure that the data is saved in a variable of the service, since due to state changes, my controller will reload all the time and I need the data only ONCE when the site loads.

  app.service('resultDeals',['$translate','$cookies','$http',
    function($translate,$cookies,$http) {

      var currentOrigin = {};
      var originsUser={};

      return {

        loadOrigins:function() {
          $http.get('app/deals/deal.json').success(function(response){
            console.log(response);
            originsUser = response.data;
            return originsUser
          }).error(function(err){
            console.log(err);
          });
        },
        userOrigin:originsUser

      };

    }]);

and my controller looks as follows

console.log(resultDeals.loadOrigins());
    $scope.updateOrigins=resultDeals.loadOrigins();

The problem is that resultDeals.loadOrigins() is always undefined.

I want to make sure to store the data obtained from loadOrigins() in a service variable and only access it from the controller when needed so that when the controller reloads the data does not have to be obtained anymore.

How can I do this?

Upvotes: 2

Views: 139

Answers (2)

Pankaj Parkar
Pankaj Parkar

Reputation: 136134

Don't use .success & .error callback function, as they don't have ability to return anything and hence they can't continue the promise chain. Instead use .then on $http.get method(which returns a promise object). That will have ability to return data while promise has been resolved or reject a promise. You could continue the promise chain from the controller method.

Service

return {
    loadOrigins: function() {
        return $http.get('app/deals/deal.json')
          .then(function(response) {
            console.log(response);
            originsUser = response.data;
            return originsUser
          }, function(err) {
            console.log(err);
          });
    },
    userOrigin: originsUser
};

Controller

resultDeals.loadOrigins().then(function(user){
   $scope.updateOrigins= user;
}, function(){
   console.log("Errror occurred.")
})

Upvotes: 2

Magus
Magus

Reputation: 15104

You have to deal with promises when you works with asynchronous code. loadOrigins must returns a promise and your controller must use it.

app.service('resultDeals',['$translate','$cookies','$http', '$q',
function($translate,$cookies,$http,$q) {

  var currentOrigin = {};
  var originsUser={};

  return {

    loadOrigins:function() {
      var deferred = $q.defer();

      $http.get('app/deals/deal.json').success(function(response){
        console.log(response);
        originsUser = response.data;
        deferred.resolve(originUser),
      }).error(function(err){
        console.log(err);
        deferred.reject();
      });

      return deferred.promise;
    },
    userOrigin:originsUser
  };

}]);

// In controller
resultDeals.loadOrigins().success(function(updateOrigins) {
    $scope.updateOrigins = updateOrigins;
}).error(function() {
    console.log('bad !');
});

Upvotes: 2

Related Questions