我正在尝试将PUT添加到ng-resource中的默认方法。到目前为止,我将DEFAULT_ACTIONS修改为:
var DEFAULT_ACTIONS = {
'get': {method:'GET'},
'save': {method:'POST'},
'update': {method:'PUT'},
'query': {method:'GET', isArray:true},
'remove': {method:'DELETE'},
'delete': {method:'DELETE'}
};
但这感觉非常黑客,显然在我更新模块时不会持续存在。有没有办法可以将更新/放置添加到将持续更新的所有ng-resource对象?
答案 0 :(得分:11)
另一种选择是配置$ resourceProvider。这将对所有$资源生效,您也需要在测试中包含此代码,很可能。
// Config the $resourceProvider
app.config(["$resourceProvider",function ($resourceProvider) {
// extend the default actions
angular.extend($resourceProvider.defaults.actions,{
// put your defaults here
query : {
method : "GET",
isArray : false,
transformResponse : function (data) {
// my data is wrapped in an object under the property "results"
return angular.fromJson(data).results;
}
}
});
}]);
答案 1 :(得分:6)
我能看到的唯一简单方法是在$ resource周围创建一个包装器:
module.factory('$myResource', ['$resource', function($resource){
return function(url, paramDefaults, actions){
var MY_ACTIONS = {
'update': {method:'PUT'}
};
actions = angular.extend({}, MY_ACTIONS , actions);
return $resource(url, paramDefaults, actions);
}
}]);
答案 2 :(得分:2)
在您的应用程序配置函数中,自定义$ resourceProvider以添加您自己的一组http actions参数,如下所示:
angular.module('app')
.config(configureResourceProvider);
function configureResourceProvider($resourceProvider){
// Provide your own set of actions on $resource factory.
// The following comments are Angular's default actions which are being
// replaced by your customized set that includes a PUT method.
//{ 'get': {method:'GET'},
// 'save': {method:'POST'},
// 'query': {method:'GET', isArray:true},
// 'remove': {method:'DELETE'},
// 'delete': {method:'DELETE'} };
$resourceProvider.defaults.actions = {
create: {method: 'POST'},
save: {method: 'POST'},
update: {method: 'PUT'},
get: {method: 'GET'},
query: {method: 'GET', isArray:true},
remove: {method: 'DELETE'},
delete: {method: 'DELETE'}
};
// Of course, you can customize other parameters too, like:
// Don't strip trailing slashes from calculated URLs
$resourceProvider.defaults.stripTrailingSlashes = false;
}
答案 3 :(得分:2)
app.config([ "$resourceProvider", function($resourceProvider) {
$resourceProvider.defaults.actions['update'] = { method: 'PUT', params: { id: '@id' }, isArray: false }
}]);