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

标签 javascript angularjs

我正在尝试使用 $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/

相关文章:

javascript - ng-repeat 元素仅在第二次运行函数后填充

angularjs - 如何在同一页面上呈现两个 angular.js View ?

javascript - 优化 JavaScript

javascript - 拆分日期值

angularjs - 如何使用 Restangular 通过 GET 发送参数数组

javascript - 更改 md-checkbox 颜色

javascript - 自动设置 cookie 值

javascript - 无法检查特定的父元素

javascript - 当我们用VueJS点击图片时,如何独立放大一张图片?

Javascript for循环写入未定义的数组