AngularJS多次处理调用promise [英] AngularJS handle calling promise multiple times

查看:137
本文介绍了AngularJS多次处理调用promise的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一项服务必须返回我国家列表。但我想将国家/地区值缓存到变量以防止多个ajax调用。
我创建了一个promise对象,但我的html必须多次调用此服务。当我调用该服务时,有时它会在从缓存返回之后第一次从ajax返回,有时它会在缓存之后从ajax重新执行3次。我该如何处理?

I have a service that must return to me countries list. But I want to cache country values to a variable to prevent multiple ajax calls. I have created a promise object but my html must call this service multiple times. When i call the service, sometimes it returns from ajax first time after that it returns from cache, sometimes it retruns from ajax 3 times after that cache. How can I handle this?

这是我的服务:

var vm = this;
vm.countries;

 vm.getCountries = function () {
    var q = $q.defer();
        if (vm.countries === undefined) {
            return $http({
                method: 'POST',
                cache: true,
                url: API + '/api/Global/Countries',
            }).then(function successCallback(response) {
                if (errorHandler(response.data)) {
                    vm.countries = response.data;
                    q.resolve(response.data)
                    console.log("ajax")
                    return q.promise;
                }
            });
        } else {
            console.log("cache")
            q.resolve(vm.countries)
            return q.promise;
        }
}


推荐答案

你可以缓存承诺而不是数据。
您可能还想考虑这里的错误情况会发生什么。需要清除缓存的承诺。

You can cache the promise instead of the data. You may also want to consider what would happen in the error case here. The cached promise would need to be cleared.

var vm = this;

function getCountries () {
    if (!vm.countryPromise) {
        vm.countryPromise = $http({
            method: 'POST',
            cache: true,
            url: API + '/api/Global/Countries',
        }).then(function successCallback(response) {
            if (errorHandler(response.data)) {
                console.log("ajax")
                return response.data;
            }
        });
    } else {
        console.log("cache")
    }
    return vm.countryPromise;
}

这篇关于AngularJS多次处理调用promise的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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