In this article, We discuss Angular HTTP POST Request Examples

Angular HTTP POST Request Examples

Angular HTTP POST Request Examples

Angular HTTP POST Request Examples
Angular HTTP POST Request Examples

Angular HTTP POST Request Examples

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

POST request with strongly typed response

This sends the same request like 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;
}

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

Angular HTTP POST Request Examples

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

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

Also Check Out Angular 8 REST API and HttpClient Examples

More Info at Angular HTTP

Angular HTTP, Angular HttpClient, Angular HttpClient Post Method, API Post Method in Angular, API Services in Angular, Angular HttpClientModule, Services Injection in Angular, Dependency Injection in Angular,

Related Posts

Leave a Reply

Your email address will not be published. Required fields are marked *

How to Protect yourself from CovidVaccination saves lives at every stage of life
  • Clean your home regularly, particularly frequently touched surfaces like
  • Stay home stay safe. Follow the Golden Rule. Wash your hands frequently with soap and water or use alchohol based hand-rub.
  • Stay home stay safe. Stay physically fit. Exercise regulary. Eat a nutritious diet. Don’t smoke.
  • Stay home stay safe. If you show symptoms of COVID-19, self isolate yourself, wear a mask around others and seek medical advice