Angular 9 HTTP POST Call Example Using Fake Backend json-server Library With JSON Parameters

 

 

Welcome folks today in this blog post we will be making a http post call in angular 9 using fake backend using the simple npm library called json-server.All the full source code of the example is shown below.

 

 

 

Get Started

 

 

 

In order to get started you need to create a new angular project by typing the below command

 

 

ng new httpcallexample

 

 

Where httpcallexample is the name of the project

 

 

And now you need to install the below node library using the npm command as shown below

 

 

npm i json-server

 

 

This will act as the fake backend for the api for which we will making the post requests in angular 9

 

 

Now create a database file name as db.json which will be the json file which will contain the records

 

db.json

 

 

{
  "people": [
    {
      "id": 1,
      "name": "Don Bradman"
    },
    {
      "id": 2,
      "name": "Sachin Tendulkar"
    }
  ]
}

 

 

Now to start the fake backend server you need to open new instance of command prompt and execute the below command

See also  AngularJS Youtube Video Embed IFrame API Video Player in Browser Using angular-youtube-embed Directive in Javascript Full Project For Beginners

 

 

json-server --watch db.json

 

 

json-server listens on port 3000

 

 

Model

 

 

Now create a Person Model class in the file called person.ts

 

 

person.ts

 

export class Person {
  id:number
  name:string
}

 

 

HTTP Post Service

 

 

import { HttpClient, HttpHeaders } from '@angular/common/http';
import { Person } from './person';
import { Injectable } from '@angular/core';
import { Observable } from 'rxjs';
 
@Injectable({providedIn:'root'})
export class ApiService {
 
  baseURL: string = "http://localhost:3000/";
 
  constructor(private http: HttpClient) {
  }
 
  getPeople(): Observable<Person[]> {
    console.log('getPeople '+this.baseURL + 'people')
    return this.http.get<Person[]>(this.baseURL + 'people')
  }
 
  addPerson(person:Person): Observable<any> {
    const headers = { 'content-type': 'application/json'}  
    const body=JSON.stringify(person);
    console.log(body)
    return this.http.post(this.baseURL + 'people', body,{'headers':headers})
  }
 
}

 

 

Template Component in HTML5

 

 

<h1>{{title}}</h1>
 
<div>
  <div>
    <label>Name: </label>
    <input [(ngModel)]="person.name" />
  </div>
  <div>
    <button (click)="addPerson()">Add</button>
  </div>
</div>
 
<table class='table'>
  <thead>
    <tr>
      <th>ID</th>
      <th>Name</th>
    </tr>
  </thead>
  <tbody>
    <tr *ngFor="let person of people;">
      <td>{{person.id}}</td>
      <td>{{person.name}}</td>
    </tr>
  </tbody>
</table>

Leave a Reply