AngularJS $http.delete encountered an error with the message "An error occurred while trying to assign a value to a read-only property 'method'."

Hello, I am diving into the world of JavaScript and AngularJS. Currently, I am working on building a simple CRUD application. Below is the code snippet from 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 entity = {};
                    entity.id = null;
                    entity.name = $scope.name;
                    entity.desc = $scope.desc;
                    entity.reg = Date.now; 
                    entity.linkImgProfile = null;
                    entity.type = null;
                    return entity;
                };

                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'
        };
    }]);
})();

The formToBean function is responsible for gathering data from the form. While the create function is functioning correctly (calling the REST service), I encountered an issue with the delete function displaying the following error:

TypeError: Cannot assign to read only property 'method' of {"id":null,"name":"john","desc":"doe","linkImgProfile":null,"type":null}

I have come across similar questions addressing this error, but I am still struggling to pinpoint the exact cause.

Answer №1

When using the delete method in $http, make sure to pass a JSON object instead of configuration-related data as the second parameter in your request. For more details, refer to the API documentation for $http.delete.

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);
    });

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Is there a way to trigger an interact.js event that will reset all draggables back to their original position at coordinates (0, 0)?

I am trying to figure out how to trigger an onmove or drag move event to reset the position of a draggable div to x:0 y: 0. Despite looking at various sources like help topics here and on interact.js main page, I haven't found the right solution yet. ...

Tips on incorporating toggle css classes on an element with a click event?

When working with Angular typescript instead of $scope, I am having trouble finding examples that don't involve $scope or JQuery. My goal is to create a clickable ellipsis that, when clicked, removes the overflow and text-overflow properties of a spec ...

PHP MySQL - Automatically trigger email notification upon insertion of a new record

Is there a way to trigger an email alert only when a new record is added, not when the user edits input fields in a table? The database I'm working with stores equipment delivery dates. Users schedule deliveries and input the dates into a SQL Server ...

What could be the reason for the absence of the loading sign in Chrome, even though it appears when the code is run on Firefox?

I implemented a function to display a loading screen on my HTML page with Google Maps integration. However, when I called the function popUpLoadingScreen() and dismissLoadingScreen() to show and hide the loading message while rendering map markers, the loa ...

How do I remove the scroll bar from the datagrid using Material UI?

https://i.stack.imgur.com/lM01l.png Is there a way to remove the scroll bar at the bottom of the page? I have already attempted using autoPageSize, but it did not solve the issue. Here is the link to the autoPageSize documentation. import { DataGrid } f ...

Is there an implicit transformation or action involved when the promise chain is resolved or rejected in $q?

Is there an intrinsic digest/apply included when the promise chain is resolved/rejected in $q? I recently switched from using $q to q in my code and it seems like a digest is no longer happening, leading to different outcomes. What could be causing this c ...

What changes can be made to the function below to ensure it reads up to 3 decimal

I am utilizing a javascript function called tafgeet to convert numbers into Arabic words. However, the issue is that it only supports up to 2 decimal places. How can I adjust the function to handle 3 decimal places? Currently, it translates numbers up to ...

Obtain the parameter value from the resolve function in ui-router

Using window.open, I plan to open a URL such as https://localhost:3000/new?HostId=8Ocs_Onuv1wowozxAAAS&_host_Info=excel%7Cweb%7C16.00%7Cen-us%7Cc8b501ce-c51d-b862-701e-5c623e1a70e0%7CisDialog. The site https://localhost:3000 hosts a MEAN stack applica ...

ng-options dependent on the value selected previously

Below is an array that I'm working with. $scope.set = [ {"name":"name1", "value":"value1"} {"name":"name2", "value":"value2"} {"name":"name3", "value":"value3"} ] I want to display options based on previous selections. For example, if I choose name1 ...

Passing an array list back to the parent component in ag-grid(Vue) - A step-by-step guide

Currently, I am integrating AG Grid with Vue. My project has a specific requirement where two checkboxes are displayed using a cellRendererFramework. However, I am facing difficulties in fetching the values of these checkboxes from the row definitions. The ...

Retrieving information and employing the state hook

Currently, my goal is to retrieve information from an API and utilize that data as state using the useState hook. fetch('https://blockchain.info/ticker') // Execute the fetch function by providing the API URL .then((resp) => resp.json()) // ...

Is Vercel deploying an incorrect version?

After working on a project for a potential employer and fixing all errors, I deployed it using Vercel. However, upon deployment, the version that was sent to me was displayed instead of the completed one I see when running npm start locally. I would great ...

Keeping track of the toggle state using a cookie

While searching for a way to retain the toggle state, I stumbled upon js-cookie on GitHub. The documentation provides instructions on creating, reading, and deleting a cookie. However, an example would have been really helpful in enhancing my understanding ...

The websocket server implemented in Node.js with the use of the "ws" library is exhibiting a peculiar behavior where it disconnects clients at random intervals,

My WebSocket server implementation is quite simple: const WebSocket = require('ws'); const wss = new WebSocket.Server( { server: server, path: "/ws" }); wss.on('connection', function connection(ws, req) { console.log("Connect ...

Differences between Javascript object constructor and object literal

Similar Questions: Creating Objects - New Object or Object Literal Notation? Literal Notation VS. Constructor to Create Objects in JavaScript As I embark on my initial Javascript tutorial journey, I have come across two distinct methods of creatin ...

Having trouble directing the focus on an HTML5 element using Javascript and Selenium webdriver

On my website, I have a specific structure in place: https://i.sstatic.net/bZhHvNlU.png Whenever the button with the ID addProfButton is clicked in the following manner: Using JavaScript: document.getElementById("addProfButton").click(); Usi ...

Vue.js component mismatch in the layout

Attempting to set up a Vue application with vuetify while incorporating layouts. As a newcomer to Vue, I may have made some beginner errors. Here is the structure of my app: main.js // The Vue build version to load with the `import` command // (runtime- ...

Utilizing jQuery to scrape HTML and dynamically manipulate elements

Is there a way to retrieve HTML content from a different subdomain and incorporate it into the current site? HTML snippet: <head> <body> <div id = "items"> <div id = "#one"> <ul> <li><a href = "#">C ...

How can I customize the styling of Autocomplete chips in MUI ReactJS?

Trying to customize the color of the MUI Autocomplete component based on specific conditions, but struggling to find a solution. Any ideas? https://i.stack.imgur.com/50Ppk.png ...

Challenges with Validating Bootstrap Datepicker Functionality

I need to restrict the datepicker input control to only allow selection of dates from the current date onwards. Despite trying to implement validation using the bootstrap-datepicker library and the following JavaScript code, I am still facing issues: $(& ...