2

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?

2 Answers 2

2

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.")
})
Sign up to request clarification or add additional context in comments.

2 Comments

Thanks for your reply. Would that not return '$http.get(...).then(...).error is not a function' ?
@user3383709 Glad to help you..Thanks :)
2

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

3 Comments

No need of creating $q.defer(); as $http.get already returns promise
If he wants to return response.data instead of response, you have to use an other promise. No ?
nope.. you could just return from the .then function, like I did..the promise chain will continue

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.