c0b*_*bra 9 javascript angularjs ngresource
我有一个$resource
API将始终返回一些需要在进入表示层之前清理的数据.具体来说,它是.NET以可爱的'/Date(...)/'
格式返回Date对象.
我不想每次打电话.query()
或写电话都要写回电.get()
.是否有某种方法可以使用一个回调来扩展资源,该回调可以在更新实例属性的REST方法上调用,或者$watch
在date属性更改时添加一些被触发的类型?基本上每件事都会发生$resource
.
angular.module('myAppServices', ['ngResource'])
.factory('Participant', ['$resource', function ($resource) {
var res = $resource('api/url/participants/:id', { id: '@id' });
// This obviously doesn't work, but something kinda like this?
res.prototype.$watch(this.FieldName, function(newVal, oldVal) {
if (needsCleaning(newVal.fieldName) {
this.FieldName = cleanupField(newVal);
}
};
});
Run Code Online (Sandbox Code Playgroud)
c0b*_*bra 12
啊哈哈,我找到了解决方法并将其留在这里.在1.1.2版本中,他们添加了将所有$http.config
选项传递给a的支持$resource
.当然,我使用的CDN没有最新版本的angular-resource.js,但是切换CDN解决了这个问题.
我刚刚使用该transformResponse
选项来修改数据.
angular.module('myAppServices', ['ngResource'])
.factory('Participant', ['$resource', '$http', function ($resource, $http) {
var res = $resource('api/url/participants/:id', { id: '@id' }, {
save: {
method: 'POST',
transformResponse: $http.defaults.transformResponse.concat([
function (data, headersGetter) {
data.FieldName = yourDateParsingFunction(data.FieldName);
return data;
}
])
}
});
Run Code Online (Sandbox Code Playgroud)
我只是将变换器添加到$httpProvider
transformResponse,它将执行所有反序列化等.
一种简单的方法是$resource
用您自己的方法覆盖您想要进行后处理的现有方法.有关示例,请参阅下面的代码和注释.
angular.module('myAppServices', ['ngResource'])
.factory('Participant', ['$resource', function ($resource) {
var res = $resource('api/url/participants/:id', { id: '@id' }, {
// create aliases for query and get to be used later
_query: { method: 'GET', isArray: true },
_get: { method: 'GET' }
});
// redefine the query method
res.query = function() {
// call the original query method via the _query alias, chaining $then to facilitate
// processing the data
res._query.apply(null, arguments).$then(function(res) {
var data = res.data;
// do any processing you need to do with data here
return data;
});
};
// redefine the method
res.get = function() {
// call the original get method via the _get alias, chaining $then to facilitate
// processing the data
res._get.apply(null, arguments).$then(function(res) {
var data = res.data;
// do any processing you need to do with data here
return data;
});
};
return res;
});
Run Code Online (Sandbox Code Playgroud)
您使用它的方式与您目前Participant
在代码中使用的方式相同,通过Participant.query()
或Participant.get()
.您在链接的$ then处理程序中返回的数据将用于解析返回的promise $resource
.
归档时间: |
|
查看次数: |
3464 次 |
最近记录: |