Sunday, March 2, 2014

My question is based on this topic in Angular Google group.
I want to provide a service which stores some basic data retrieved from the backend via $http, then I only need to fetch those data once. like,
var load = function() {
   return $http.get(...).then(function(data) {
       return data.user; 
   });
};

module.factory("userProvider", function() {
    var user;
    var getUser = function() {
        if(!user) {
            load().then(function(data) {
               user = data;
           });
        }
        return user;
    };
    return {
        getUser : getUser
    }
});

module.controller("UserController", ["userProvider", function UserController("userProvider") {
    var user = userProvider.getUser();
    // do something with user
}]);
The problem is that the promise chain ends in userProvider but not in controller, so the user is undefined the first time I use this controller since the data has not been returned.
How can I use such a storage service and return the data correctly? Thanks!
share|edit
add comment

2 Answers

You can just create your own promise. Here is the modified code:
module.factory("userProvider", function($q) {
  var user,
      getUser = function() {
    var deferred = $q.defer();
    if(!user) {
      getUser().then(function(data) {
        user = data;
        deferred.resolve(user);
      });
    } else {
      deferred.resolve(user);
    }

    return deferred.promise;
  };

  return {
    getUser : getUser
  };
});
share|edit
 
Thanks Josh, it works! –  Edward Jan 15 '13 at 10:54
add comment
It's a bit of an overhead to create your own promise, angular's $http creates one for you anyway. What you're looking for is caching and http can handle it for you by passing cache:true to the service call.
So you can simply do something like this:
 module.factory("userProvider", function() {
   var getUser = function() {
   return $http.get(..., {cache:true}).then(function(data) {
       return data.user; 
   });

   return {
       getUser : getUser
   }
});
share|edit
add comment

4 comments:

  1. AngularJS is an incredible tool Angularjs Online Training development tricks and methods AngularJS Interview Questions AngularJS application Angularjs Training in Chennai Data Binding Angular.js Course Root Scope and Extending Scope Angularjs Training

    ReplyDelete