2017-01-02 2 views
0

각도의 http 캐시를 사용하려고하지만 결과가 정의되지 않았습니다. 캐시는 객체를 반환하지만 usersCache는 정의되지 않습니다. data.js에 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(); 
}); 

서비스

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 비동기입니다. 요청이 완료되어 동 기적으로 캐시에 액세스하려고 시도 할 때까지는 캐시되지 않습니다. – charlietfl

답변

1

@charlietfl 맞다.

$ HTTP는 asynchronous.Nothing 요청 완료 될 때까지 캐시을 받고 기적 캐시에 액세스하려고합니다. ,

먼저 this.explorePosts 기능 $http 서비스가 alredy 반환 promise을 반환합니다

은 예상대로이 작업을합니다.

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

실제로 캐시 만족도가 실제로 필요하지 않습니다. 서비스에서 'then()'이 제거 된 경우')'컨트롤러는 항상 응답 객체를 볼 수 있지만 캐시 설정으로 인해 하나의 요청 만 이루어질 수 있습니다. – charlietfl

+0

이것이 맞습니다.하지만 OP는 교육 목적으로 캐시를 탐색하려고합니다. – djxak

+0

맞았습니다. 그것은 영업 이익으로 인식하지 못할 수도 있습니다 – charlietfl

관련 문제