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
你能分享攔截器代碼嗎? –