Published: November 21 2019
Last updated: November 08 2022

Angular - HTTP POST Request Examples

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

Other HTTP examples available:


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

This sends an HTTP POST request to the Reqres api which is a fake online REST api that includes a /api/posts route that responds to POST requests with the contents of the post body and an id property. The 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 can handle any properties returned in the response.

ngOnInit() {
    this.http.post<any>('https://reqres.in/api/posts', { title: 'Angular POST Request Example' }).subscribe(data => {
        this.postId = data.id;
    })
}

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


POST 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() {          
    this.http.post<Article>('https://reqres.in/api/posts', { title: 'Angular POST Request Example' }).subscribe(data => {
        this.postId = data.id;
    })
}

...

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

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


POST 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 POST Request Example' };
    this.http.post<any>('https://reqres.in/api/posts', body, { headers }).subscribe(data => {
        this.postId = data.id;
    });
}

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


POST request with error handling

The below examples show two different ways of handling an error from an HTTP POST request in Angular. They both send the same request to an invalid url on the api then assign the error to the errorMessage component property and log it to the console. The difference is how the error is caught, the first uses the subscribe error callback, the second uses the catchError operator.


Using the error callback to the RxJS subscribe method

The subscribe() method is passed an observer object with two callback functions, the next() function is called if the request is successful, the error() function is called if the request fails.

There is also a complete() function that we're not using here, it gets called after an Observable successfully emits its final value, i.e. after the next() function for an HTTP request. In this case it wouldn't be called because the Observable errors out.

ngOnInit() {
    this.http.post<any>('https://reqres.in/invalid-url', { title: 'Angular POST Request Example' }).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-post-request-examples?file=src/app/components/post-request-error-handling-callback.component.ts


Using the RxJS catchError operator

The Observable response from the POST request is piped to the catchError operator which handles the error and returns a new Observable that doesn't emit any values.

The function passed to subscribe() is called if the request is successful, it's the equivalent of passing an observer object with only a next() function. It isn't called here because no values are emitted after the error is handled, the Observable simply completes.

RxJS Operators

Operators in RxJS accept an input Observable and return an output Observable, multiple can be piped together in the Observable chain and they are executed before values are emitted to subscribers. With the catchError operator you have the added options of returning a fallback value to subscribers when there is an error, or rethrowing a custom error using the RxJS throwError() function. For more info on RxJS operators see https://rxjs.dev/guide/operators.

ngOnInit() {
    this.http.post<any>('https://reqres.in/invalid-url', { title: 'Angular POST Request Example' })
        .pipe(catchError((error: any, caught: Observable<any>): Observable<any> => {
            this.errorMessage = error.message;
            console.error('There was an error!', error);

            // after handling error, return a new observable 
            // that doesn't emit any values and completes
            return of();
        }))
        .subscribe(data => {
            this.postId = data.id;
        });
}

Example Angular component at https://stackblitz.com/edit/angular-post-request-examples?file=src/app/components/post-request-error-handling-catch-error.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: 'app', templateUrl: 'app.component.html' })
export class AppComponent implements OnInit {
    postId;

    constructor(private http: HttpClient) { }

    ngOnInit() {      
        // Simple POST request with a JSON body and response type <any>
        this.http.post<any>('https://reqres.in/api/posts', { title: 'Angular POST Request Example' }).subscribe(data => {
            this.postId = data.id;
        })
    }
}

 

Update History:

  • 8 Nov 2022 - Updated examples to Angular 14.2.9. The previous version (Angular 8.0.1) is still available at https://stackblitz.com/edit/angular-http-post-examples.
  • 7 Nov 2022 - Added error handling example with RxJS catchError operator
  • 22 Apr 2021 - Replaced JSONPlaceholder API with Reqres API because JSONPlaceholder stopped allowing CORS requests
  • 28 May 2020 - Posted video to YouTube of HTTP POST request examples with Angular at https://youtu.be/w2HFuzxxkRs
  • 16 Jan 2020 - Added example of how to set HTTP headers on the request
  • 21 Nov 2019 - Created Angular HTTP POST request examples

 


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