Have multiple calls wait on the same promise in Angular

不打扰是莪最后的温柔 提交于 2019-12-12 11:21:08

问题


I have multiple controllers on a page that use the same service, for the sake of example we will call the service USER.

The first time the USER.getUser() is called it does an $http request to GET data on the user. After the call is completed it stores the data in USER.data. If another call is made to USER.getUser() it checks if there is data in USER.data and if there is data it returns that instead of making the call.

My problem is that the calls to USER.getUser() happen so quickly that USER.data does not have any data so it fires the $http call again.

Here is what I have for the user factory 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;
        }
    }
});

I hope my question makes sense. Any help would be much appreciated.


回答1:


Does this work for you?

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



回答2:


$http already returns the promise for you, even more, in 2 useful types: success & error. So basically, the option that @kfis offered does NOT catch errors and not flexible. You could write something simple:

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


来源:https://stackoverflow.com/questions/29421123/have-multiple-calls-wait-on-the-same-promise-in-angular

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!