gpt4 book ai didi

javascript - 如何缓存 $http 响应以便在 angularjs 中重用

转载 作者:行者123 更新时间:2023-12-03 07:21:31 25 4
gpt4 key购买 nike

我正在尝试使用 $http.get() 响应作为提供给 Controller 的服务。请帮忙!

erp.service('elementData',['$http', '$cacheFactory', function($http, $cacheFactory){
var fetchCache = $cacheFactory('ele', {number: 1});

$http({url: "./php/fetchElement.php",
method: 'GET'}).success(function(data){
fetchCache.put(1, data.records);
console.log(fetchCache.info('ele'));
//return fetchCache.get(1);
});
console.log(fetchCache.info('ele'));



}])

console.log(fetchCache.info('ele'));提供不同的结果。

最佳答案

为了有效地缓存来自 HTTP 调用的响应,并返回该响应(如果存在),我会这样做

angular.module('app').factory('dataService', dataService);
dataService.$inject = ['$http', '$q'];

function dataService($http, $q) {
var service = {
getGroups: getGroups,
_groupCache: null
};

return service;

function getGroups() {
// Return from local cache variable if we have it.
if (service._groupCache) return $q.resolve(service._groupCache);
// Otherwise, return from API.
return $http.get("api/ms/groups/").then(
function (response) {
service._groupCache = response.data;
return response.data;
}
);
}

然后可以将其注入(inject)到您的 Controller 中并按如下方式使用:

angular.module('app').controller('PageCtrl', PageCtrl);

PageCtrl.$inject = ['dataService'];

function PageCtrl(dataService) {
var vm = this;
// "Public" properties
vm.groups = null;
dataService.getGroups().then(function (groups) {
vm.groups = groups;
});
}

然后您应该可以访问页面内的群组。第一次运行此代码时,服务上的 _groupCache 将为 null,因此它将发送 HTTP 请求。在后续运行中,将填充 _groupCache。您可以通过将缓存的组存储在浏览器的本地存储中来进一步优化这一点,这样即使在页面加载后也可以保持缓存。

请注意,getGroups 函数的返回始终是异步的,因此任何需要该数据的内容都应链接到 getGroups 返回时的 .then 上,如本例所示。

在您的示例中,.success 回调将异步执行,因此第二个 console.log 将在第一个 console.log 之前执行。要解决这个问题,您可以重写如下:

erp.service('elementData',['$http', '$cacheFactory', function($http, $cacheFactory){
var fetchCache = $cacheFactory('ele', {number: 1});

$http({url: "./php/fetchElement.php",
method: 'GET'}).then(function(data){
fetchCache.put(1, data.records);
console.log(fetchCache.info('ele'));
}).then(function () {
console.log(fetchCache.info('ele'));
});
}])

关于javascript - 如何缓存 $http 响应以便在 angularjs 中重用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36196762/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com