Below is a quick set of examples to show how to send HTTP DELETE requests from Angular to a backend API.

Simple DELETE request

This sends an HTTP DELETE request to the JSONPlaceholder api which is a fake online REST api that includes a /posts/1 route that responds to DELETE requests with a HTTP 200 OK response. When the response is received the Angular component displays the status message ‘Delete successful’.

ngOnInit() {
    this.http.delete('https://jsonplaceholder.typicode.com/posts/1')
        .subscribe(() => this.status = 'Delete successful');
}

Example Angular component at https://stackblitz.com/edit/angular-http-delete-examples?file=app/components/delete-request.component.ts

DELETE request with error handling

This sends a request to an invalid url on the api then assigns the error to the errorMessage component property and logs the error to the console.

The object passed to the request subscribe() method contains two callback functions, the next() function is called if the request is successful and the error() function is called if the request fails.

ngOnInit() {
    this.http.delete('https://jsonplaceholder.typicode.com/invalid-url')
        .subscribe({
            next: data => {
                this.status = 'Delete successful';
            },
            error: error => {
                this.errorMessage = error.message;
                console.error('There was an error!', error);
            }
        });
}

Example Angular component at https://stackblitz.com/edit/angular-http-delete-examples?file=app/components/delete-request-error-handling.component.ts

DELETE request with headers set

This sends the same request again with a couple of headers set, the HTTP Authorization header and a custom header My-Custom-Header.

The below headers are created as a plain javascript object, they can also be created with the HttpHeaders class, e.g. const headers = new HttpHeaders({ 'Authorization': 'Bearer my-token', 'My-Custom-Header': 'foobar' })

To set or update headers on an existing HttpHeaders object call the set() method, e.g. const headers = new HttpHeaders().set('Authorization', 'Bearer my-token')

ngOnInit() {
    const headers = { 'Authorization': 'Bearer my-token', 'My-Custom-Header': 'foobar' };
    this.http.delete('https://jsonplaceholder.typicode.com/posts/1', { headers })
        .subscribe(() => this.status = 'Delete successful');
}

Example Angular component at https://stackblitz.com/edit/angular-http-delete-examples?file=app/components/delete-request-headers.component.ts

#angular #api #web-development #programming #javascript

How to Send HTTP DELETE Requests from Angular to Backend API
28.00 GEEK