AngularJS에서 HTTP 'Get'서비스 응답을 캐시 하시겠습니까?
데이터 객체가 비어있을 때 HTTP 'Get'요청을하고 성공시 데이터 객체를 채우는 사용자 정의 AngularJS 서비스를 만들 수 있기를 원합니다.
다음에이 서비스를 호출 할 때 HTTP 요청을 다시하는 오버 헤드를 우회하고 대신 캐시 된 데이터 개체를 반환하고 싶습니다.
이것이 가능한가?
Angular의 $ http 에는 캐시가 내장되어 있습니다. 문서에 따르면 :
cache – {boolean | Object} – HTTP 응답의 캐싱을 활성화 또는 비활성화하기 위해 $ cacheFactory로 생성 된 부울 값 또는 객체 입니다. 자세한 내용은 $ http 캐싱을 참조하십시오 .
부울 값
그래서 당신은 설정할 수 있습니다 cache
에 사실 의 옵션에서 :
$http.get(url, { cache: true}).success(...);
또는 구성 유형의 통화를 선호하는 경우 :
$http({ cache: true, url: url, method: 'GET'}).success(...);
캐시 객체
캐시 팩토리를 사용할 수도 있습니다.
var cache = $cacheFactory('myCache');
$http.get(url, { cache: cache })
$ cacheFactory를 사용하여 직접 구현할 수 있습니다 (특히 $ resource를 사용하는 경우).
var cache = $cacheFactory('myCache');
var data = cache.get(someKey);
if (!data) {
$http.get(url).success(function(result) {
data = result;
cache.put(someKey, data);
});
}
지금은 더 쉬운 방법이 있다고 생각합니다. 이렇게하면 모든 $ http 요청 ($ resource가 상속 함)에 대한 기본 캐싱이 가능합니다.
var app = angular.module('myApp',[])
.config(['$httpProvider', function ($httpProvider) {
// enable http caching
$httpProvider.defaults.cache = true;
}])
현재 안정적인 버전 (1.0.6)에서이 작업을 수행하는 더 쉬운 방법은 훨씬 적은 코드가 필요합니다.
모듈을 설정 한 후 공장을 추가하십시오 :
var app = angular.module('myApp', []);
// Configure routes and controllers and views associated with them.
app.config(function ($routeProvider) {
// route setups
});
app.factory('MyCache', function ($cacheFactory) {
return $cacheFactory('myCache');
});
이제 이것을 컨트롤러에 전달할 수 있습니다 :
app.controller('MyController', function ($scope, $http, MyCache) {
$http.get('fileInThisCase.json', { cache: MyCache }).success(function (data) {
// stuff with results
});
});
한 가지 단점은 키 이름도 자동으로 설정되어 까다로울 수 있다는 것입니다. 그들이 키 이름을 얻기 위해 어떤 방법으로 추가하길 바랍니다.
Check out the library angular-cache if you like $http's built-in caching but want more control. You can use it to seamlessly augment $http cache with time-to-live, periodic purges, and the option of persisting the cache to localStorage so that it's available across sessions.
FWIW, it also provides tools and patterns for making your cache into a more dynamic sort of data-store that you can interact with as POJO's, rather than just the default JSON strings. Can't comment on the utility of that option as yet.
(Then, on top of that, related library angular-data is sort of a replacement for $resource and/or Restangular, and is dependent upon angular-cache.)
As AngularJS factories are singletons, you can simply store the result of the http request and retrieve it next time your service is injected into something.
angular.module('myApp', ['ngResource']).factory('myService',
function($resource) {
var cache = false;
return {
query: function() {
if(!cache) {
cache = $resource('http://example.com/api').query();
}
return cache;
}
};
}
);
angularBlogServices.factory('BlogPost', ['$resource',
function($resource) {
return $resource("./Post/:id", {}, {
get: {method: 'GET', cache: true, isArray: false},
save: {method: 'POST', cache: false, isArray: false},
update: {method: 'PUT', cache: false, isArray: false},
delete: {method: 'DELETE', cache: false, isArray: false}
});
}]);
set cache to be true.
참고URL : https://stackoverflow.com/questions/14117653/cache-an-http-get-service-response-in-angularjs
'Programing' 카테고리의 다른 글
Java 8 스트림의 .min () 및 .max () : 왜 컴파일됩니까? (0) | 2020.04.30 |
---|---|
dyld : 라이브러리가로드되지 않았습니다… 이유 : 이미지를 찾을 수 없습니다 (0) | 2020.04.30 |
직렬화 할 수없는 작업 : 객체가 아닌 클래스에서만 클로저 외부에서 함수를 호출 할 때 java.io.NotSerializableException (0) | 2020.04.30 |
변수가 클래스인지 아닌지 확인하는 방법? (0) | 2020.04.30 |
PHP에서 yield는 무엇을 의미합니까? (0) | 2020.04.30 |