AngularJS $http.delete broke in "TypeError: Cannot assign to read only property 'method' .."

Fra*_*sco 2 javascript angularjs

I'm new to JavaScript and AngularJS. I'm tryin' to build up a very simple CRUD application. Here is the code of my controller:

(function() {
    var app = angular.module('form.user', []);

    app.directive('formusergui', [function(){
        return {
            restrict: 'E',
            templateUrl: './js/views/user.form.html',
            controller: function($scope, $http) {

                this.formToBean = function() {
                    var ent = {};
                    ent.id = null;
                    ent.name = $scope.name;
                    ent.desc = $scope.desc;
                    ent.reg = Date.now; 
                    ent.linkImgProfile = null;
                    ent.type = null;
                    return ent;
                };

                this.create = function() {      
                    $http.post('./services/users', JSON.stringify(this.formToBean()))
                    .success(function(data, status, headers, config) {
                        $scope.esito = "success: " + JSON.stringify(data);
                    })
                    .error(function(data, status, headers, config) {
                        $scope.esito = "error: " + JSON.stringify(data);
                    });
                };

                this.delete = function() {
                    $http.delete('./services/users', JSON.stringify(this.formToBean()))
                    .success(function(data, status, headers, config) {
                        $scope.esito = "success: " + JSON.stringify(data);
                    })
                    .error(function(data, status, headers, config) {
                        $scope.esito = "error: " + JSON.stringify(data);
                    });
                };
                ...
            },
            controllerAs: 'userForm'
        };
    }]);
})();
Run Code Online (Sandbox Code Playgroud)

formToBean function collects data by the form. As the create function works well (REST service is called), the delete function broke with this error:

TypeError: Cannot assign to read only property 'method' of {"id":null,"name":"john","desc":"doe","linkImgProfile":null,"type":null}
Run Code Online (Sandbox Code Playgroud)

I found similar questions about this kind of error but still I can't get what's going wrong.

小智 5

对于$ http中的delete方法,第二个参数是一个配置,在你的请求而不是配置相关的数据中,简单的json对象被传递,请参考$ http.delete的api

https://docs.angularjs.org/api/ng/service/ $ http#delete

$http.delete('./services/users/:idtodelete')
   .success(function(data, status, headers, config) {
        $scope.esito = "success: " + JSON.stringify(data);
    });
Run Code Online (Sandbox Code Playgroud)