Angular HTTP POST Example

In this Angular Http Post Example, we will show you how to make an HTTP Post Request to a back end server. We use the HttpClient module in Angular. The Angular introduced the HttpClient Module in Angular 4.3. It is part of the package @angular/common/http.  We will create a Fake backend server using JSON-server for our example. We also show you how to add HTTP headers, parameters or query strings, catch errors, etc.

HTTP Post Example

Create a new Angular App.

Import HttpClientModule

Import the HttpClientModule & FormsModule in app.module.ts. Also, add it to the imports array.

Faking Backend

In the HTTP Get example, we made use of the publicly available GitHub API. For this example, we need a backend server, which will accept the post request.

There are few ways to create a fake backend. You can make use of an in-memory web API or the JSON server. For this tutorial, we will make use of the JSON Server.

Install the JSON-server globally using the following npm command

create a db.json file with some data. The following example contains data of people with id & name fields.

Start the server

The json-server starts and listens for requests on port 3000.

fake back-end for HTTP post using json-server

Browse the URL http://localhost:3000/ and you should be able to see the home page

The URL http://localhost:3000/people lists the people from the db.json. You can now make GET POST PUT PATCH DELETE OPTIONS against this URL

Model

Now, back to our app and create a Person model class under person.ts

HTTP Post Service

Now, let us create a Service, which is responsible to send HTTP Requests. Create a new file api.service.ts and copy the following code

The URL endpoint of our json-server is hardcoded in our example, But you can make use of a config file to store the value and read it using the APP_INITIALIZER token

We inject the HttpClient using the Dependency Injection

The getPeople() method sends an HTTP GET request to get the list of persons. Refer to the tutorial Angular HTTP GET Example to learn more.

In the addPerson method, we send an HTTP POST request to insert a new person in the backend.

Since we are sending data as JSON, we need to set the 'content-type': 'application/json' in the HTTP header. The JSON.stringify(person) converts the person object into a JSON string.

Finally, we use the http.post() method using URL, body & headers as shown below.

The post() method returns an observable. Hence we need to subscribe to it.

Component

Template

The template is very simple.

We ask for the name of the person, which we want to add to our backend server. The two-way data binding ([(ngModel)]="person.name") keeps the person object in sync with the view.

Code

In the refreshPeople() method, we subscribe to the getPeople() method of our ApiService to make an HTTP get() request to get the list of people.

Under the addPerson() method, we subscribe to the apiService.addPerson(). Once the post request finishes, we call refreshPeople() method to get the updated list of people.

HTTP Post in Action

Angular HTTP Post Example using httpclient Module

HTTP Post syntax

The above code is a very simple example of the HTTP post() method. The complete syntax of the post() method is as shown below. The first two arguments are URL and body. It has the third argument options, where we can pass the HTTP headers, parameters, and other options to control how the post() method behaves.

  • headers : use this to send the HTTP Headers along with the request
  • params: set query strings / URL parameters
  • observe: This option determines the return type.
  • responseType: The value of responseType determines how the response is parsed.
  • reportProgress: Whether this request should be made in a way that exposes progress events.
  • withCredentials: Whether this request should be sent with outgoing credentials (cookies).

observe

The POST method returns one of the following

  1. Complete response
  2. body of the response
  3. events.

By default, it returns the body.

Complete Response

The following code will return the complete response and not just the body

events

You can also listen to progress events by using the { observe: 'events', reportProgress: true }. You can read about observe the response

Response Type

The responseType determines how the response is parsed. it can be one of the arraybufferjson blob or text. The default behavior is to parse the response as JSON.

Strongly typed response

Instead of any, we can also use a type as shown below

String as Response Type

The API may return a simple text rather than a JSON. Use responsetype: 'text' to ensure that the response is parsed as a string.

Catching Errors

The API might fail with an error. You can catch those errors using catchError. You either handle the error or throw it back to the component using the throw err

Read more about error handling from Angular HTTP interceptor error handling

Transform the Response

You can make use of the mapfilter RxJs Operators to manipulate or transform the response before sending it to the component.

URL Parameters

The URL Parameters or Query strings can be added to the request easily using the HttpParams option. All you need to do is to create a new HttpParams class and add the parameters as shown below.

The above code sends the GET request to the URL http://localhost:3000/people?para1=value1&para2=value2

The following code also works.

HTTP Headers

You can also add HTTP Headers using the HttpHeaders option as shown below. You can make use of the Http Interceptor to set the common headers. Our example code already includes an HTTP header

Send Cookies

You can send cookies with every request using the withCredentials=true as shown below. You can make use of the Http Interceptor to set the withCredentials=true for all requests.

Summary

This guide explains how to make use of HTTP post in Angular using an example app

16 thoughts on “Angular HTTP POST Example”

  1. Great post! The step-by-step explanation of the Angular HTTP POST implementation made it much clearer. I appreciate the code snippets you provided; they were really helpful for understanding how to set up the request. Looking forward to more tutorials like this!

  2. import { Component, OnInit } from ‘@angular/core’;
    import { ActivatedRoute,Params,Router } from ‘@angular/router’;
    import { ApiService } from ‘../api.service’;
    import { datamodol } from ‘../list/model’;

    @Component({
    selector: ‘app-update’,
    templateUrl: ‘./update.component.html’,
    styleUrl: ‘./update.component.css’
    })
    export class UpdateComponent implements OnInit {
    public dataid!:number;
    public employee!: datamodol;
    constructor(private activatedroute:ActivatedRoute, private router:Router, private api:ApiService){}
    ngOnInit(): void {
    this.activatedroute.paramMap.subscribe((param:Params)=>{
    this.dataid=param[‘get’](“id”);
    console.log(“Data Id is “,this.dataid)

    })
    this.api.fetchdata(this.dataid).subscribe((data:datamodol)=>{
    this.employee=data;
    })

    }

    update(){
    this.api.updateemployee(this.employee,this.dataid).subscribe((res:datamodol)=>{
    this.router.navigate([“/”])
    })
    }
    }

    1. i started json server (json-server –watch db.json), but “http://localhost:3000/people” returns me parenthesis {} only.

      Ma be this will help you, what problem i am getting. or where i am doing wrong.

  3. I have deployed my angular node app on heroku and i’m trying to call node api for getting data from backend, but getting http error response.
    It was working fine locally, can somebody help me in that?…
    i was calling like this..

    getAll(): Observable {
    return this.http.get(baseUrl1);
    }

  4. Please, what if your Json structure is instead this :
    {
    “people”: [
    {
    “id”: 1,
    “name”: “Don Bradman”,
    “school”: {
    “name”: “college”,
    “class”: 5
    }
    },

    ]
    }

    How would the HTML form look like?????

Leave a Comment

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

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Scroll to Top