在Angular中有多个调用等待相同的诺言 [英] Have multiple calls wait on the same promise in Angular

查看:49
本文介绍了在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;
            }
        }
    })

这篇关于在Angular中有多个调用等待相同的诺言的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆