2017-01-02 80 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