angularjs: 리소스 개체에 캐시를 추가하는 방법
http 내부에 캐시를 추가하는 것은 매우 간단합니다.(cache=true를 전달함으로써)
http://docs.angularjs.org/api/ng.$http에는 캐시 옵션이 있습니다.
어떻게 하면 동일한 기능을 angularjs의 $리소스에 추가할 수 있습니까?
1.1.2(commit) 이후 모든 $httpConfig 옵션이 $resource 작업 개체에 직접 표시됩니다.
return {
Things: $resource('url/to/:thing', {}, {
list : {
method : 'GET',
cache : true
}
})
};
AngularJs에서 자체 캐시를 구현하는 것은 매우 쉽습니다.$cacheFactory 사용:
app.factory('myService', function($resource, $cacheFactory) {
var cache = $cacheFactory('myService');
var User = $resource('/user/:userId', {userId:'@id'});
return {
getResource: function(userId) {
var user = cache.get(userId);
if (!user) {
user = User.get({userId:userId});
cache.put(userId, user);
}
return user;
}
};
});
docs 상태에서는 $resource는 $cacheFactory를 기본적으로 지원합니다.를 통해 전달할 수 있습니다.cache의 속성: "Displayed" :
cache–{boolean|Cache}- 약약true: " "$http는 캐시에 됩니다.GET않은 캐시 가 "로 작성된 )$cacheFactory이 캐시는 캐시에 사용됩니다.
사용 예:
app.factory('Todos', function($resource, $cacheFactory) {
var todosCache = $cacheFactory('Todos');
return $resource(apiBaseUrl + '/todos/:id', {id: '@id'}, {
'get': { method:'GET', cache: todosCache},
'query': { method:'GET', cache: todosCache, isArray:true }
});
});
이 내용은 여기에 기재되어 있지 않지만 기본 메서드를 덮어쓸 수도 있습니다.
app.factory("List", ["$resource", function($resource) {
return $resource("./lists/:path/:action.json", {}, {
get: {
method: "GET",
cache: true
}
});
}]);
$http에 기본 캐시를 설정할 수도 있습니다.따라서 이를 기반으로 $리소스에 기본 캐시를 설정할 수도 있습니다.
LocalStorage가 가능하고 $cacheFactory에 준거한 뛰어난 각도 캐시 설정:
app.run(function($http, DSCacheFactory) {
DSCacheFactory('defaultCache', {
deleteOnExpire: 'aggressive',
storageMode: 'localStorage'
});
$http.defaults.cache = DSCacheFactory.get('defaultCache');
});
angular-resource 소스는 현재 작성된 방식으로는 캐시를 트리거할 수 없음을 나타냅니다.
소스로부터의 요청 오브젝트는 다음과 같습니다.
$http({
method: action.method,
url: route.url(extend({}, extractParams(data), action.params || {}, params)),
data: data
}).then(...)
이 문제를 해결할 수 있는 몇 가지 방법이 있습니다.
먼저 클라이언트 측 지속성을 사용하여 로컬로 캐시할 수 있습니다.wrapper와 함께 amplife.store를 사용합니다(b/c API 구문은 별로 마음에 들지 않습니다).찾고 있는 항목과 타겟이 되는 브라우저에 따라 다양한 스토리지 솔루션이 있습니다.잔디 의자를 이용하는 사람도 꽤 있습니다.
그런 다음 모델을 문자열화 및 로컬에 저장하고 원하는 규칙이나 시간 제한에 따라 업데이트할 수 있습니다.
또 다른 해결책은 단순히 각도 리소스를 수정하여 원하는 매개 변수를 수용하는 것입니다.이것은 단순할 수도 있고($리소스에 인수를 추가하는 것만으로), 필요한 만큼 복잡할 수도 있습니다.
예.
function ResourceFactory(url, paramDefaults, actions, cache) {
...
var cache = cache != null ? cache : false; // Set default to false
$http({
method: action.method,
url: route.url(extend({}, extractParams(data), action.params || {}, params)),
data: data,
cache: cache
}).then(...)
}
마지막으로 요건에 따라 angular.factory를 사용하여 자체 리소스를 쉽게 생성할 수 있습니다.ngResource의 장점 중 하나는 파라미터를 변환할 때 모든 문자열 보간이 작동한다는 것입니다.그러나 필요한 경우 이 논리를 구문 분석용으로 바로 이동하거나 사용 중인 모델에 따라 직접 작성할 수 있습니다.
'각캐시드 리소스'라는 아주 잘 생각해낸 모듈을 방금 발견했는데, 이 모듈을 사용하면 도움이 될 것입니다.https://github.com/goodeggs/angular-cached-resource
localStorage를 사용한 캐시 관리 기능이 추가되어 $리소스를 대체할 수 없습니다.브라우저가 로컬 스토리지를 지원하지 않는 경우 캐싱의 이점을 얻을 수 없습니다.다음은 사용 방법의 예입니다.
$resource를 사용하는 기존 방법:
var Entry = $resource('/entries/:slug', {slug: '@slug'});
var announcement = new Entry();
announcement.slug = 'announcing-angular-cached-resource';
announcement.title = 'Announcing Angular Cached Resource';
announcement.body = 'Here is why Angular Cached Resource is awesome!';
announcement.$save(function() {
alert('Saved announcement.');
});
$cached Resource를 사용하는 새로운 방법:
var Entry = $cachedResource('entries', '/entries/:slug', {slug: '@slug'});
var announcement = new Entry();
announcement.slug = 'announcing-angular-cached-resource';
announcement.title = 'Announcing Angular Cached Resource';
announcement.body = 'Here is why Angular Cached Resource is awesome!';
announcement.$save(function() {
alert('Saved announcement.');
});
코드의 차이는 다음과 같습니다.
- $resource 대신 $cachedResource 사용
- '키'를 제공하다(
entries위의 예에서는)를 참조하면 페이지 새로고침 또는 새로고침 사이에도 참조할 수 있습니다.이러한 엔트리는 개봉 후 localStorage를 사용하기 때문에 유지됩니다.
상세한 튜토리얼은, https://github.com/goodeggs/bites/blob/master/src/documents/open_source/2014-04-24-angular-cached-resource.md 를 참조해 주세요.
또한 Angular 2.0은 다음과 같은 기능을 즉시 지원할 수 있습니다.
각도 리소스 1.5.5를 사용하고 있으며 코드를 다음과 같이 설정합니다.
요약
작업을 쿼리로 설정합니다. "쿼리" 작업은 어레이로 역직렬화된 응답을 예상하므로 isArray를 명시적으로 true로 설정해야 합니다.기본적으로는 ngResource 작업은 쿼리를 제외한 개체를 기대합니다.여기를 참조해 주세요.
컨트롤러
angular.module("app")
.controller('myCtrl',['$scope','myService',function($scope, myService) {
$scope.myData= myService.myResource.query();
}]);
서비스
angular.module('app')
.factory('myService',['$resource',function($resource){
var baseUrl = 'http://www.MyExample.com/';
return{
myResource:$resource(baseURL + '/myEndpoint/:id', {id:'@id'},{
'query':{
method:'GET',
cache:'true',
isArray:true
}}),
}
}]);
언급URL : https://stackoverflow.com/questions/12225475/angularjs-how-to-add-caching-to-resource-object
'programing' 카테고리의 다른 글
| WordPress에서 모든 포스트 태그를 얻으려면 어떻게 해야 하나요? (0) | 2023.03.10 |
|---|---|
| 홈 화면에 추가하기 위한 iOS 아이콘이 검은색으로 바뀝니다. (0) | 2023.03.10 |
| wp-admin은 공백 페이지를 표시하는데, 어떻게 수정해야 합니까? (0) | 2023.03.10 |
| 그라들 - 주 클래스를 찾거나 로드할 수 없습니다. (0) | 2023.03.10 |
| 왜 java.lang이 뜨죠?DB에 BLOB를 로드하려고 할 때 AbstractMethodError가 발생합니까? (0) | 2023.03.10 |