2013-11-15 89 views
10

我正在使用djang-tastypie作爲後端,AngularJs用於前端。我正在使用angularjs $ http向CRUD發送請求。 GET,POST,PUT一切正常,但是當我嘗試發送PATCH請求時,出現錯誤Method PATCH未定義。我創建了一個api調用的工廠,但PATCH請求在那裏不起作用。使用angularjs修補請求

angular.module('tastypieModule', ['ngResource']). 
factory('apiCall', function($http, $resource) { 

    delete $http.defaults.headers.common['X-Requested-With']; 

    var apiCall = $resource('/api/v1/:type/:id/', 
     {type: '@type', username: '@userName', api_key: '@api_key', user: '@userID', id: '@id'}, 
     { 
      get: {method: 'GET'}, 
      post: {method: 'POST', headers: {'Content-Type': 'application/json'}}, 
      del: {method: 'DELETE', headers: {'Content-Type': 'application/json'}}, 
      update: {method: 'PUT', headers: {'Content-Type': 'application/json'}}, 
      pupdate:{method:'PATCH',headers: {'Content-Type': 'application/json'}} 
     } 
    ); 

return apiCall; 
}); 
function MyCtrl($scope,$resource){ 
$scope.edit=function(){ 
    id=$scope.E_id 
    $http.pupdate('/api/v1/quizsetting/'+id+'/', editedquizsetting). 
    success(function(data, status) { 
     $scope.status = status; 
     $scope.data = data; 
     $scope.editQuizSettingModal = false; 
     //$scope.quizsettinglist.objects[$scope.e_quizsettingindex]=data; 
     $(".message").append("object has been created successfully"); 
    }) 
    . 
    error(function(data, status) { 
     $scope.data = data || "Request failed"; 
     $scope.status = status;   
    }); 
}; 
} 

這是我的HTML代碼

<div ng-app="myApp"> 
<div ng-controller="MyCtrl"> 
<button type="button" ng-click="edit()">Edit</button> 
</div></div> 

當我將在控制檯中使用此代碼路徑請求它顯示http.patch不是一個函數。 告訴我如何配置ng-app和服務以使用angularjs發送PATCH請求。

+2

的[配置angularjs模塊發送補丁請求]可能重複(http://stackoverflow.com/questions/20305615/configure-angularjs-module -to-發送貼片請求) – kynan

回答

18

將PATCH添加到AngularJS的一個常見問題是,它沒有該HTTP方法的默認Content-Type頭(對於PUT,POST和DELETE,應用程序/ json; charset = utf-8)。而這些都是我的$ httpProvider配置中添加補丁支持:

module.config(['$httpProvider', function($httpProvider) { 
$httpProvider.defaults.headers.patch = { 
    'Content-Type': 'application/json;charset=utf-8' 
} 
}])