pas*_*ine 7 angularjs ngresource
是否可以将虚拟属性添加到ngResource?我创建了这样的服务
app.factory('Person', ['$resource', function($resource) {
return $resource('api/path/:personId', {
personId: '@_id'
}, {
update: {
method: 'PUT'
}
});
}])
Run Code Online (Sandbox Code Playgroud)
Person有一个属性name和一个属性surname.
我想fullname通过添加fullname返回的虚拟属性来检索resource.name + resource surname.
我知道我可以在控制器中添加它,但是将它添加到服务中会使它更加便携.我试过这样的事
app.factory('Person', ['$resource', function($resource) {
return $resource('api/path/:personId', {
personId: '@_id'
}, {
update: {
method: 'PUT'
},
fullname: function(resource){
return resource.name + ' ' + resource.surname;
}
});
});
}])
Run Code Online (Sandbox Code Playgroud)
但它不起作用.
您可以尝试拦截来自 Person 资源的响应并增强响应。像这样:
app.factory('Person', ['$resource', function($resource) {
function getFullName(){
return this.name + ' ' + this.surname;
};
return $resource('api/path/:personId', {
personId: '@_id'
}, {
update: {
method: 'PUT'
},
'get': {method:'GET', isArray:false,interceptor:{
'response': function(response) {
response.fullname = getFullName; //augment the response with our function
return response;
}
}}
});
}]);
Run Code Online (Sandbox Code Playgroud)