Multiple calls await the same promise in Angular

I have several controllers on a page using the same service, for example, we will call the USER service.

The first time USER.getUser () is called, it requests a $ http request for GET data for the user. Upon completion of the call, it saves the data in USER.data. If another call is made in USER.getUser (), it checks to see if there is data in USER.data, and if there is data, they return it instead of making a call.

My problem is that USER.getUser () calls are so fast that USER.data has no data, so it starts calling $ http again.

Here is what I have for the factory user right now:

.factory("user", function($http, $q){
    return {
        getUser: function(){
            var that = this;
            var deferred = $q.defer();
            if(that.data){
                deferred.resolve(that.data);
            } else {
                $http.get("/my/url")
                .success(function(res){
                    that.data = res;
                    deferred.resolve(that.data);
                });
            }
            return deferred.promise;
        }
    }
});

Hope my question makes sense. Any help would be greatly appreciated.

+4
2

?

.factory("user", function($http, $q) {
        var userPromise;

        return {
            getUser: function () {
                if (userPromise) {
                    return userPromise;
                }

                userPromise = $http
                    .get("/my/url")
                    .then(function(res) {
                        return res.data;
                    });

                return userPromise;
            }
        }
    })
+9

$http , , 2 : . , , , @kfis, . - :

.factory('user', function($http) {
    return {
       getUser: function() {
          $http.get('/my/url/')
             .success(function(data) {
                return data;
             })
             .error(function(err) {
                // error handler
             })
       }
    }
})
+1

All Articles