2017-01-02 103 views
0

我想使用角的http缓存,但结果是未定义的。缓存返回一个对象,但用户缓存未定义。

在main.js控制器

app.controller('exploreController', function($scope, dataService, $cookies, $cacheFactory, $http) { 
// dataService.explorePosts(); 

$scope.explore = function(){ 
    dataService.explorePosts(); 
    var cache = $cacheFactory.get('$http'); 
    console.log(cache); 
    var usersCache = cache.get('http://dstm.herokuapp.com/api/explore'); 
    console.log(usersCache); 

}; 

$scope.explore(); 
}); 

服务在data.js

angular.module('dsnApp') 
.service('dataService', function($http, $cookies, $cacheFactory) { 
    this.explorePosts = function(){ 
    var id = $cookies.get("userId"); 
    $http.get('http://dstm.herokuapp.com/api/explore', {cache: true, 
    params: {userId: id, page: 1}, 
    }) 
    .then(function successCallback(response) { 
    console.log(response); 
    }, function errorCallback(response) { 
    console.log(response); 
    }); 
}; 
+0

控制器* *? – MACMAN

+0

您可以创建一个工作** plnkr – Aravind

+2

$ http是asynchronous.nothing将被缓存,直到请求完成,并且您试图同步访问缓存 – charlietfl

回答

1

@charlietfl是正确的。

$ HTTP是asynchronous.Nothing将被缓存,直到请求 完成,而您试图同步访问缓存。

为了让你想到这个工作:

首先,使this.explorePosts函数返回promise,这$http服务alredy返回。

this.explorePosts = function(){ 
    var id = $cookies.get("userId"); 
    return $http.get('http://dstm.herokuapp.com/api/explore', {cache: true, 
     params: {userId: id, page: 1}, 
    }) 
    .then(function successCallback(response) { 
     console.log(response); 
    }, function errorCallback(response) { 
     console.log(response); 
    }); 
    }; 

然后使用在承诺的then回调缓存。

$scope.explore = function() { 
    dataService.explorePosts().then(function() { 
     var cache = $cacheFactory.get('$http'); 
     console.log(cache); 
     var usersCache = cache.get('http://dstm.herokuapp.com/api/explore'); 
     console.log(usersCache); 
    }); 
}; 
( 'exploreController',[ '$范围', '$ cacheFactory',函数($范围,DataService的,$饼干,$ cacheFactory,$ HTTP){
+0

实际上,甚至不需要cachefactory。如果在服务中remove() )'in controller would always see the response object,但只有一个请求会因高速缓存配置而生成 – charlietfl

+0

这是对的,但我认为OP只是想为教育目的探索缓存。 – djxak

+0

对,刚才提到因为OP可能也不知道 – charlietfl