在AngularJs中,如何从缓存中添加/删除$resource项

In AngularJs, how to add/remove $resource items to/from the cache

本文关键字:删除 resource 添加 AngularJs 缓存      更新时间:2023-09-26

我有一个$资源,我用来获取一个或所有注册,创建新的或更新现有的注册,删除注册…的作品。下面是资源的代码:

    .factory('Registrations', function ($resource) {
        return $resource('api/registrations/:assetType/:registrationId',
            {assetType: '@assetType', registrationId: '@assetRegistrationId'},
            {query: {
                method: 'GET',
                cache: true,
                isArray: true
            }}
        );
    })

正如您所看到的,缓存已经到位,并且工作得很好:后续请求不会传播到服务器。除了……在创建或删除注册后,缓存不会更新。

对于移除,我已经提出了这个解决方案。看起来很糟糕,但很有效。这里有一些奇怪的事情需要注意:

        Registrations.delete({assetType: $scope.assetType, registrationId: registration.assetRegistrationId}, function () {
            //doesn't seem to work -> dirty hack
            //$cacheFactory.get('$http').remove('api/registrations/' + $scope.assetType + '/' + registration.registrationId);
            var cached = $cacheFactory.get('$http').get('api/registrations/' + $scope.assetType);
            var cachedRegistrations = JSON.parse(cached[1]);
            var registrationInCache = get(cachedRegistrations, registration.assetRegistrationId);
            if (registrationInCache) {
                cachedRegistrations.splice(cachedRegistrations.indexOf(registrationInCache), 1);
                cached[1] = JSON.stringify(cachedRegistrations);
            }
            $scope.registrations = Registrations.query({assetType: $scope.assetType});
            //...

令人惊讶的是,缓存没有保存javascript对象的列表,而只有一个条目,其中包含一个实际字符串,表示所有条目的json。然后我要做的是对该字符串进行字符串化,删除已删除的项并再次对列表进行字符串化。

对于创建,我没有那么有创意,我只能删除缓存中的一个条目(代表完整的集合),并从服务器重新加载所有数据。下面是我如何使缓存失效的方法:

$cacheFactory.get('$http').remove('api/registrations/' + $scope.assetType);

我可能错过了一些明显的东西。有人有什么建议或澄清吗?谢谢!

我认为这种缓存应该在服务器端完成,而不是在前端(AngularJS)。我不是100%确定Angular的cache=true是如何工作的,但我相信它只是缓存了结果,所以其他请求将获得缓存的结果。Angular无法判断服务器上的数据何时发生了变化。