Consuming Web API REST with Angular 2: Implementing Http delete method with custom Headers

After switching to Angular 2 Release, I started using Http and Headers from @angular/http. Everything seemed to be working fine as I called verbs like POST, GET, and PUT. However, I ran into an issue when trying to use the "DELETE" verb.

Here is a snippet of my code:

remove(url:string, id:any) {
   let headers = new Headers();
   headers.append('Authorization': 'Bearer ' + this.token);
   return this.http.delete(url, {
        headers: headers;
        body: { id: id }
   }).map(response => response.json());
}

The response I received stated that the requested resource does not support the http method 'delete'.

In my controller, the method looks something like this:

[HttpDelete]
public Task<HttpResponseMessage> Delete(int id)
{
    //..
}

I would appreciate any assistance in resolving this issue. Thank you!

Answer №1

To solve my issue, I found success using a query string approach like this:

remove(urlController:string, id:any){
   let headers = new Headers();
   headers.append('Authorization': 'Bearer ' + this.token);
   return this.http.delete(urlController + '/?id=' + id, {
    headers: headers;
    }).map(response => response.json());
}

For instance:

remove(urlController:string, id:any){
   let headers = new Headers();
   headers.append('Authorization': 'Bearer ' + this.token);
   return this.http.delete('users'+ '/?id=' + '2', {
    headers: headers;
    }).map(response => response.json());
}

Answer №2

One issue that arises is the necessity for your API server to permit the use of the HTTP DELETE Method. Upon initiating an HTTP DELETE Request, your browser first sends an HTTP OPTIONS to the server; subsequently, the server responds with a header Access-Control-Allow-Methods containing the list of permissible methods.

To address this, you must issue an OPTION Response Header akin to the following:

Access-Control-Allow-Methods: DELETE

To acquire further insights, refer to: CORS support for PUT and DELETE with ASP.NET Web API

Answer №3

When encountering an issue with my custom httpService that extends from the base http service, I found a solution by simply modifying the URL string. This change resolved the problem for me:

this.httpService.delete(`${API_URL}Favorites/${id}`)

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

React Scheduler by Bryntum

After successfully discovering some functions related to various actions, I find myself still in need of additional functions: Currently, I am utilizing these functions by passing them directly as props to the Scheduler React Component: - onBeforeEventSa ...

Utilizing Regular Expressions in Angular 4 by Referencing Patterns Stored in an Object

I'm facing an issue where my code is functional, but I keep encountering a Tslint error that's proving difficult to resolve. This particular configuration worked fine with Angular 1, but now I'm in the process of migrating the application to ...

Troubleshooting Cors Problem between Angular 2 Form Data and Express

I'm attempting to send some files to an Express server that utilizes the cors() module in the following way app.use(cors()); This is the Angular 2 code used for file uploading let formData:FormData = new FormData(); for(let i = 0; i < files. ...

Angular 2's Conditional Validation: A Comprehensive Guide

Angular 2 offers straightforward validation, which is a great feature. However, the challenge lies in making a required field optional based on another field's selection. Below are the validation rules: this.contractsFilter = this.fb.group({ selec ...

Unable to iterate over a JSON response from a POST request in Angular 8

I am attempting to iterate through a JSON object that is returned after making a POST request to my REST API. However, I'm encountering the following error: DatetodateComponent.html:33 ERROR Error: Cannot find a differ supporting object '[objec ...

Strategies for Handling Errors within Observable Subscriptions in Angular

While working with code from themes written in the latest Angular versions and doing research online, I've noticed that many developers neglect error handling when it comes to subscription. My question is: When is it necessary to handle errors in an ...

"Use Windsor to resolve or register a generic object based on a specified string identifier

In my project, I have a specific interface called IImportCommand<T> public interface IImportCommand<T> where T : ImportModelBase { DateTime Date { get; set; } List<T> Items { get; set; } } which is implemented by the object Impor ...

The 'errorReason' property is not found within the 'MessageWithMdEnforced' type

I am currently working on a project using meteor, react, and typescript. Here is the section of code that is causing an error: {message?.errorReason && <div>{message?.errorReason}</div> } The error message I am encountering is: "P ...

The provider 'SqlServer-20' does not have any associated metadata details available

Exploring the SQL database capabilities of Quartz.NET 3.0 for .NET Core has hit a roadblock. I am encountering an issue with configuring the StdSchedulerFactory correctly. Each time I try to call StdSchedulerFactory.GetScheduler, the following exception is ...

Configurations for POP3 settings in C# on devMail.Net

As someone who is not a programmer and just starting to learn C, I'm facing an issue with our application that uses DevMail.Net to fetch pop3 mail. My service provider recently changed the pop3 port from "110" to "125", causing it to malfunction. Desp ...

The `setValue` function seems to be malfunctioning in my Angular application

Currently, I am in the process of developing a web application using MEAN Stack with Angular 6. One of the functionalities I am trying to implement involves populating form fields with default values when a specific button is clicked. Below is the HTML for ...

Loader for dynamically loading tabs in Angular 2

I am looking to develop a dynamic tabs loader using Angular 2 material with specific syntax support. <generic-tabs [tabs]="tabs" tabVisibleField="name"> <test-cmp [tabContent] testData="hello"></test-cmp> ...

The Stopwatch feature in the System.Diagnostics does not always accurately show the elapsed time

Utilizing the System.Diagnostics.Stopwatch, I am measuring the time taken by two distinct operations within my program. This specific program is designed to identify all prime numbers up to a user-specified input. Upon testing with a large input, such as ...

Issue encountered: Failed to scroll Selenium element into view with error code 34 while using NUnit framework with C#

Encountering an error while trying to click on an <a> tag in a regression test script, resulting in the issue mentioned in the title. I have delved into the problem both here: Selenium::WebDriver::Error::MoveTargetOutOfBoundsError: Element cannot be ...

Creating rectangular shapes on the canvas with the help of react hooks

I have a React+Typescript web application and I am currently working on implementing the functionality to draw rectangles on a canvas. My goal is to utilize React hooks instead of classes in order to achieve this. The desired outcome is to enable the user ...

Convert the Inner property of the class into a Json object using c#serialization

Here are the classes I am working with: public class ClassOne { [JsonProperty(PropertyName = "property1", NullValueHandling = NullValueHandling.Ignore)] public string Prop1 { get; set; } [JsonProperty(PropertyName = "prope ...

Guide on utilizing a provider's variable in another provider within Ionic 2/3

In my code, I have a boolean variable called isConnection that is used to monitor network connection status. This variable is defined in a provider named 'network' and can be set to either true or false in different functions. Now, I need to acc ...

How to extract data from an alert in an Ionic application

I am currently working with Ionic 3 and I have a requirement to implement autocomplete using Google Maps on an input field. Below is the alert that I have in my .ts file: let alert = this.alertCtrl.create({ title: 'Offer a Ride', inputs: ...

Retrieve the IDs of all children and grandchildren within a parent ID using Typescript

If I were to have an array of objects containing hierarchical data: const data = [ { groupId: 1, parentGroupId: null }, { groupId: 2, parentGroupId: 1 }, { groupId: 3, parentGroupId: 1 }, { groupId: 4, parentGroupId: null }, { groupId: 5, parentG ...

Determining the Success of an SQL Server Automated Upgrade Using a C# WinForms Application

Currently, I am in the process of automating the upgrade from SQL Server 2005 Express to SQL Server 2008R2 Express using a WinForms application that is specifically designed for upgrading our software. Our software is operational at over 800 locations, hen ...