Programming

AngularJS에서 $ resource 캐시를 새로 고침 / 무효화하는 방법

procodes 2020. 8. 28. 19:12
반응형

AngularJS에서 $ resource 캐시를 새로 고침 / 무효화하는 방법


다음과 같이 기본 $ http 캐시 구현을 사용하는 간단한 사용자 $ resource가 있습니다.

factory('User', function($resource){
    return $resource(endpoint + '/user/current/:projectId', {},
        {get: 
            {
                cache: true,
                method: 'GET'
            }
        }
    );
})

이것은 매우 잘 작동합니다. 즉, 내 서버가 내 응용 프로그램에서 한 번만 호출 된 다음 캐시에서 값을 가져옵니다.

하지만 특정 작업 후에 서버에서 값을 새로 고쳐야합니다. 그렇게하는 쉬운 방법이 있습니까?

감사.


부울을 유지하고 $http캐시를 가져옵니다 .

var $httpDefaultCache = $cacheFactory.get('$http');

그런 다음 $cacheFactory아래에 제공된 사용 인스턴스 인 로 만든 다른 캐시처럼 제어 할 수 있습니다.

$httpDefaultCache.remove(key);
// Where key is the relative URL of your resource (eg: /api/user/current/51a9020d91799f1e9b8db12f)

cache각각 속성에 부울 인수를 사용하는 대신 $ cacheFactory로action 생성 된 캐시 인스턴스를 전달하여 더 많은 제어를 할 수 있습니다 (즉, 캐시 지우기).

사용 예 :

app.factory('Todos', function($resource, $cacheFactory) {
    var cache = $cacheFactory('todo');
    return $resource(apiBaseUrl + '/todos/:id', { id: '@id' }, {
        'get': { method: 'GET', cache: cache  },
        'query': { method: 'GET', cache: cache, isArray: true }
    });
});

비슷한 것을 찾고있는이 스레드를 발견했지만 $ resource가 자동으로 캐시를 관리하므로 캐시를 강제로 지울 필요가 없습니다.

쿼리 할 수있는 리소스가있는 경우 해당 쿼리 응답이 캐시되지만 동일한 리소스에 대해 무언가를 저장하는 경우 이전에 캐시 된 데이터가 유효하지 않아야하므로 삭제됩니다. 이런 식으로 작동 할 것입니다.

이 작업을 수행하는 데 사용하는 코드는 다음과 같습니다 (이상해 보이는 팩토리 생성 부분을 무시하고 "클래스"본문에주의를 기울일 수 있습니다).

'use strict';

sampleApp.players.$ng.factory('sampleApp.players.PlayerService', [
    '$log',
    '$resource',
    sampleApp.players.PlayerService = function ($log, $resource) {
        var service = {};

        $log.info('Creating player resource.');
        var Player = $resource('/api/players', {}, {query: {
            isArray: true,
            cache: true,
            method: 'GET'
        }});

        service.addPlayer = function(playerName) {
            $log.info('Saving a new player.');
            return new Player({name: playerName}).$save();
        };

        service.listPlayers = function () {
            $log.info('Fetching players.');
            return Player.query();
        };

        return service;
    }]);

If you call the listPlayers function several times, the first call makes a http get request and all subsequent calls are cached. If you call addPlayer though, a http post is performed as expected, and then the next call to listPlayers will perform a http get (not cached).

This keeps you out of the business of managing someone else's ($http) cache and trying to keep up with which url's are being used for requests and which are clearing caches at the right times.

I suppose the moral of the story here is to work with the library and all will be well... except for any bugs or incomplete features, but Angular doesn't have any of those ;)

p.s. This is all running on AngularJS 1.2.0.

참고URL : https://stackoverflow.com/questions/17059569/how-to-refresh-invalidate-resource-cache-in-angularjs

반응형