3
是否有一种方法可以在请求中使用X-HTTP-Method-Override
或_method
参数来执行http方法覆盖,角度为$resource
服务?AngularJs http方法覆盖PUT-POST
是否有一种方法可以在请求中使用X-HTTP-Method-Override
或_method
参数来执行http方法覆盖,角度为$resource
服务?AngularJs http方法覆盖PUT-POST
在您的资源工厂中,您可以为每种类型的请求指定方法。
angular.module('myServices', ['ngResource'])
.factory('Customer', function($resource){
return $resource('../api/index.php/customers/:id', {id:'@id'}, {
update: {method:'PUT'}
});
})
是标准的方法,但你可以使用这个太:
angular.module('myServices', ['ngResource'])
.factory('Customer', function($resource){
return $resource('../api/index.php/customers/:id', {id:'@id'}, {
update: {params: {'_method':'PUT', id: '@id'}}
});
})
万一别人是寻找一个代码片段,那就是:
(function(module) {
function httpMethodOverride($q) {
var overriddenMethods = new RegExp('patch|put|delete', 'i');
return {
request: function(config) {
if (overriddenMethods.test(config.method)) {
config.headers = config.headers || {};
config.headers['X-HTTP-Method-Override'] = config.method;
config.method = 'POST';
}
return config || $q.when(config);
}
};
}
module.factory('httpMethodOverride', httpMethodOverride);
module.config(function($httpProvider) {
$httpProvider.interceptors.push('httpMethodOverride');
});
})(angular.module('app-module'));
谢谢!我已经解决了,使用请求拦截器来转换请求,这样我就不需要更改已经写好的代码了,我可以禁用它来注释拦截器 – rascio
你能分享拦截器代码吗? –