javascript - AngularJS 处理多次调用 Promise,但有一些异常(exception)

标签 javascript angularjs ajax

我之前问过这个问题(AngularJS handle calling promise multiple times),现在我有不同的障碍。现在我必须获取城市列表,但有一个异常(exception)。

城市可以像国家一样被多次调用(在我的老问题中),我必须缓存数据以防止多次调用相同的数据(城市)。老问题的解决方案可以阻止多个调用,但现在我必须允许一些调用(对于新国家的城市)。

所以我的问题是: 如何缓存城市数据以防止调用相同的数据? (我的函数必须捕获调用是否是针对新国家/地区的城市列表。如果是:调用服务并获取城市,如果不是:从缓存中返回城市)

这是我的服务:

var cityCache = {};
vm.getCities = function (countryCode) {

    if (countryCode!=undefined && !cityCache[countryCode]) {

        vm.cityPromise = $http({
            method: 'POST',
            cache: true,
            url: API + '/api/Global/CountryCities',
            data: {
                "CountryCode": countryCode
            }
        }).then(function successCallback(response,countryCode) {
            if (errorHandler(response.data)) {
                console.log("cities come from ajax")
                cityCache[response.config.data.CountryCode] = response.data;
                console.log(cityCache)
                return response.data
            }
        });
    } else {
        vm.cityPromise = $timeout(function () {//I use this to get promise object
            return cityCache[countryCode]
        }, 0)
        console.log("cities comes from cache");
    }

    return vm.cityPromise;
}

示例: 假设我同时调用 getCities 函数 3 次。我正在通过 chrome 查看我的网络流量。我看到 3 个 ajax 调用。这是正常的。但有时,我会调用同一个城市。我需要编辑我的函数,该函数可以理解之前是否已经调用过城市数据(某种缓存)。
例如:如果我用这个参数询问函数 3 次:

1-给我德国的城市,
2-给我爱尔兰的城市,
3-(再次)给我德国的城市,

已经打了3次电话了但我想要 1 个德国电话,1 个爱尔兰电话。只需 2 个电话。

最佳答案

与您的其他问题的答案相同,只需将国家/地区代码映射到 promise 即可。 也和以前一样,考虑错误情况。

var vm = this;

vm.cityPromises = {};

function getCities(countryCode) {
    if (!vm.cityPromises[countryCode]) {
        vm.cityPromises[countryCode] = $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.cityPromises[countryCode];
}

关于javascript - AngularJS 处理多次调用 Promise,但有一些异常(exception),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38308915/

相关文章:

javascript - 将calculateWinner() 设为辅助函数而不是组件的理由是什么?

angularjs - 如何在 API 和 Angular 客户端之间启用 CORS

javascript - Django - 使用 Ajax 重新加载数据表

jQuery ajax 无法使用 'blob' 数据类型

Javascript - 范围问题和将参数传递给动态创建的事件处理程序

Javascript SELECT BOX 选项依赖于所选的其他 SELECT BOX 选项

html - 如何使用 ng-repeat 渲染这个不规则的表格?

javascript - 从 ajax 调用 Controller - Typo3

javascript - IE 7/8 javascript排序错误 "Number Expected"

javascript - 如何在 ui-router AngularJS 中使用组件模板?