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

查看:21
本文介绍了有多个调用在 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天全站免登陆