在Angular中有多个调用等待相同的诺言

在Angular中有多个调用等待相同的诺言

问题描述:

我在一个页面上有多个使用同一服务的控制器,为了举例说明,我们将服务称为USER.

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

第一次调用USER.getUser()时,它会执行$ http请求以获取用户数据.调用完成后,它将数据存储在USER.data中.如果再次调用USER.getUser(),它将检查USER.data中是否有数据,并且是否有数据,而不是进行调用.

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.

我的问题是,对USER.getUser()的调用发生得太快,以至于USER.data没有任何数据,因此它再次触发$ http调用.

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.

这对您有用吗?

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