Published: October 07 2020

Angular - HTTP PUT Request Examples

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

Other HTTP examples available:


Simple PUT request with a JSON body and response type <any>

This sends an HTTP PUT request to the JSONPlaceholder api which is a fake online REST api that includes a /posts/1 route that responds to PUT requests with the contents of the put request body and the post id property. The post id from the response is assigned to the local postId property in the subscribe callback function.

The response type is set to <any> so it handle any properties returned in the response.

ngOnInit() {
    const body = { title: 'Angular PUT Request Example' };
    this.http.put<any>('https://jsonplaceholder.typicode.com/posts/1', body)
        .subscribe(data => this.postId = data.id);
}

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


PUT request with strongly typed response

This sends the same request as the above but sets the response type to a custom Article interface that defines the expected response properties.

ngOnInit() {          
    const body = { title: 'Angular PUT Request Example' };
    this.http.put<Article>('https://jsonplaceholder.typicode.com/posts/1', body)
        .subscribe(data => this.postId = data.id);
}

...

interface Article {
    id: number;
    title: string;
}

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


PUT 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() {
    const body = { title: 'Angular PUT Request Example' };
    this.http.put<any>('https://jsonplaceholder.typicode.com/invalid-url', body)
        .subscribe({
            next: data => {
                this.postId = data.id;
            },
            error: error => {
                this.errorMessage = error.message;
                console.error('There was an error!', error);
            }
        });
}

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


PUT 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' };
    const body = { title: 'Angular PUT Request Example' };
    this.http.put<any>('https://jsonplaceholder.typicode.com/posts/1', body, { headers })
        .subscribe(data => this.postId = data.id);
}

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


Prerequisites for making HTTP requests from Angular

Before making HTTP requests from your Angular app you need to do a couple of things.

1. Add the HttpClientModule to the imports array of your AppModule like below on lines 3 and 10.

import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { HttpClientModule } from '@angular/common/http';

import { AppComponent } from './app.component';

@NgModule({
    imports: [
        BrowserModule,
        HttpClientModule
    ],
    declarations: [
        AppComponent
    ],
    bootstrap: [AppComponent]
})
export class AppModule { }


2. Import the HttpClient into your component and add it to the constructor() params like below on lines 2 and 8.

import { Component, OnInit } from "@angular/core";
import { HttpClient } from '@angular/common/http';

@Component({ selector: 'put-request', templateUrl: 'put-request.component.html' })
export class PutRequestComponent implements OnInit {
    postId;

    constructor(private http: HttpClient) { }

    ngOnInit() {
        const body = { title: 'Angular PUT Request Example' };
        this.http.put<any>('https://jsonplaceholder.typicode.com/posts/1', body)
            .subscribe(data => this.postId = data.id);
    }
}

 


Need Some Angular Help?

Search fiverr for freelance Angular developers.


Follow me for updates

On Twitter or RSS.


When I'm not coding...

Me and Tina are on a motorcycle adventure around Australia.
Come along for the ride!


Comments


Supported by