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





  "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






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





export class Person {



HTTP Post Service



import { HttpClient, HttpHeaders } from '@angular/common/http';
import { Person } from './person';
import { Injectable } from '@angular/core';
import { Observable } from 'rxjs';
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);
    return + 'people', body,{'headers':headers})



Template Component in HTML5



    <label>Name: </label>
    <input [(ngModel)]="" />
    <button (click)="addPerson()">Add</button>
<table class='table'>
    <tr *ngFor="let person of people;">

Leave a Reply