是否可以在过滤器中使用angularjs缓存的资源方法?
Is it possible to use angularjs cached resource method in a filter?
作用域中有一个外部对象id的属性,还有一个将这个id扩展为完整对象的过滤器,如下所示:
{{ typeId | expandType }}
过滤器:.filter('expandType', ['TypeService', function (tsvc) {
return function (id) {
return tsvc.types.get({ id: id });
}
}])
其中tsvc.types.get()是添加了缓存选项的普通资源获取方法。
.factory('TypeService', ['$resource', function ($resource) {
var typeResource = $resource('/api/types/:id', { id: '@id' }, {
get: { method: 'GET', cache: true, params: { id: '@id' } }
});
return {
types: typeResource
}
}])
据我所知,angular在第一个之后运行额外的摘要只是为了确保没有改变。但很明显,在下一个摘要中,过滤器返回了一个不同的对象,我得到了infdig错误(摘要在无限循环中执行)。
我希望,如果资源被缓存,它将返回相同的对象从缓存所有的时间。我可以确认,在执行get()时,只有一次访问服务器,因此缓存正在工作。
我能做些什么来使它工作,并使用过滤器将id扩展到完整的对象?
虽然可以,但将承诺绑定到视图通常不是一个好主意。在您的示例中,过滤器对每个摘要重新求值,并引用https://docs.angularjs.org/api/ng/service/$http:
当启用缓存时,$http将来自服务器的响应存储在指定的缓存中。下次发出相同的请求时,从缓存中提供响应,而不向服务器发送请求。
请注意,即使响应是从缓存中提供的,数据的传递也是异步的,就像实际请求一样。
说明一下,ngResource在内部使用了$http
。
你仍然可以使用过滤器从你的控制器调用它:
app.filter('expandType', function ($http) {
return function (id) {
return $http.get('data.json');
};
});
app.controller('MainCtrl', function ($scope, expandTypeFilter) {
var typeId = 'hello';
expandTypeFilter(typeId).success(function (data) {
$scope.expandedTypeId = data[typeId];
});
});
砰砰作响:http://plnkr.co/edit/BPS9IY?p=preview。
使用这种方法,如果缓存响应的唯一原因是为了避免对服务器的重复调用,那么现在可以停止缓存它,以便稍后获得新的数据,但这当然取决于您的需要。
我真的很想使用过滤器,因为它在整个应用程序中都在使用,我不想让我的控制器混乱。在这一点上,我得出的解决方案如下:
.filter('expandType', ['TypeService', function (tsvc) {
var cache = {};
return function (id) {
if (!id) {
return '';
}
var type = cache[id];
if (!type) {
tsvc.types.get({ id: id }).$promise.then(function (data) {
cache[id] = data;
});
cache[id] = {}
return cache[id];
}
else {
return type;
}
}
}])
相关文章:
- 如何清除angularjs中的缓存
- 在Angularjs服务中为返回对象引用的http请求提供的数据构建简单的缓存
- 如何缓存$http响应以便在angularjs中重用
- AngularJS控制器正在Firefox和IE中缓存:如何禁用
- AngularJS :从$http获取缓存结果
- angularJS缓存数据
- AngularJS 工厂函数无法访问本地存储的缓存变量
- 如何缓存$http但也能够在angularjs中删除
- 当我“拉取刷新”时,如何清理缓存?使用Ionic Framework和AngularJS
- REST 服务缓存策略与 AngularJS.
- AngularJS$resource和缓存工厂
- 在AngularJS中缓存国际化JSON数据
- 当promise中发生错误时,数据缓存在服务器或客户端上,或者根本不缓存在AngularJS中
- AngularJS回调,复制$http的行为.将缓存转化为承诺
- 无法在AngularJS服务中检索缓存的jQuery选择器
- AngularJS承诺正在缓存
- 如何在运行应用程序时用javascript清除AngularJS应用程序中的缓存
- 在AngularJS中,您将如何缓存从Java收到的数据(例如,今天的前10条新闻的列表)
- 如何缓存AngularJS的ui-router解析
- 避免在IE中缓存angularJS的部分视图