Spread the love

In this tutorial, we are going to call the rest API’s using the angular HttpClient. Angular has vast features and library to call the web or rest API’s.

Before start i assume you know to installation of angular.

Follow the below steps to call the APIs:

Step 1 : Create a new project

Create a project rest-api using ng new command.

ng new rest-api

it will ask few questions and will create the project.

Step 2 : Create a Component

Create a new component using ng g command or manually.

 ng g component rest-api

Above command will create the component in /src/app/rest-api. Here, we will get 4 files component, html, Unit test and css. we can also create the component and all files manually with same name.

  1. rest-api.component.html
  2. rest-api.component.ts
  3. rest-api.component.css
  4. rest-api.component.spec.ts

Step 3 : Import HttpClientModule in Main Module of component(app.module.ts)

import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core'; 
import { HttpClientModule } from '@angular/common/http'; // <-- important module for http

import { AppComponent } from './app.component';
import { RestApiComponent } from './rest-api/rest-api.component';

@NgModule({
  declarations: [
    AppComponent,
    RestApiComponent
  ],
  imports: [
    BrowserModule,
    HttpClientModule //import here
  ],
  providers: [],
  bootstrap: [AppComponent]
})
export class AppModule { }

This is the most important step to do otherwise angular will throw below error

NullInjectorError: StaticInjectorError(AppModule)[RestApiComponent -> HttpClient]:

Step 4 : Open component file

Open /src/app/rest-api/rest-api.component.ts and start editing it. you need to import below modules in component.

  1. @angular/common/http : To make http request
  2. rxjs : Reactive programming using observables and catch the errors

Next, Inject HttpClient in constructor and make a function callRestApi.

import { Component, OnInit } from '@angular/core';
import { HttpHeaders, HttpClient } from '@angular/common/http';
import { catchError, map } from 'rxjs/operators';
import { throwError } from 'rxjs';

@Component({
  selector: 'app-rest-api',
  templateUrl: './rest-api.component.html',
  styleUrls: ['./rest-api.component.css']
})
export class RestApiComponent implements OnInit {

  constructor(private http: HttpClient) { }

  ngOnInit() {
  }

}

Calling GET Rest Api, we are going to create a function to call GET api.

callJsonGetRestApi(url):Observable<any> {
   
    
    return this.http.get(url)
      .pipe(map((data: any) => {
      //handle api 200 response code here or you wanted to manipulate to response
        return data;

      }),
        catchError((error) => {    // handle error
         
          if (error.status == 404) {
            //Handle Response code here
          }
          return throwError(error);
        })
      );

  }

Next, Calling POST json api , to send the json post request to server.


callJsonDataRestApi(url: string, form: Object) {

    

    return this.http.post(url,form)
      .pipe(map((data: any) => {
      //handle api 200 response code here or you wanted to manipulate to response
        return data;

      })
      ,
       catchError((error) => {    // handle error
         
          if (error.status == 404) {
            //Handle Response code here
          }
          return throwError(error);
        })
      );

}

We can also send form data to server to get the post data in $_POST in php

callFormDataRestApi(url: string, form: Object) {

  let formData = form;//{name:"test",email:"test@yxyz.com"};
  const uploadData = new FormData();
  for (let i in form) {
    if (form[i] instanceof Blob) // check is file
      uploadData.append(i, form[i], form[i].name ? form[i].name : "");
    else if (form[i] instanceof Array) { //check type of Array

      for (let arr in form[i]) {
        for (let lst in form[i][arr]) {
          if (form[i][arr][lst] instanceof Blob) { // check is file
           
            uploadData.append("" + i + "[" + arr + "][" + lst + "]", form[i][arr][lst], form[i][arr][lst].name ? form[i][arr][lst].name : "");
          }
          else {
            uploadData.append("" + i + "[" + arr + "][" + lst + "]", form[i][arr][lst]);
          }
        }
      }
    }
    else
      uploadData.append(i, form[i]);
  }
  formData = uploadData
  let headers = new HttpHeaders({
   'Authorization': 'Bearer your_token'   //add your api token for auth
  }).set('Content-Type', []);

  return this.http.post(url,formData, { headers: headers})
    .pipe(map((data: any) => {
    //handle api 200 response code here or you wanted to manipulate to response
      return data;

    })
    ,
     catchError((error) => {    // handle error
       
        if (error.status == 404) {
          //Handle Response code here
        }
        return throwError(error);
      })
    );

}  

Above method is useful when we wanted to call the apis of php server. This method will send request as Content-Type: multipart/form-data;

Let’s implement all in Component

import { Component, OnInit } from '@angular/core';
import { HttpHeaders, HttpClient } from '@angular/common/http';
import { catchError, map } from 'rxjs/operators';
import { throwError, Observable } from 'rxjs';
@Component({
  selector: 'app-rest-api',
  templateUrl: './rest-api.component.html',
  styleUrls: ['./rest-api.component.css']
})
export class RestApiComponent implements OnInit {

  constructor(private http: HttpClient) { }
  callJsonGetRestApiResponse: string;
  callJsonDataRestApiResponse: string;
  callFormDataRestApiResponse: string;
  ngOnInit() {

       
      
  }

  onClick(type:string="callJsonGetRestApi"){
    if(type=="callJsonGetRestApi"){
      this.callJsonGetRestApi("https://reqres.in/api/users").subscribe(data=>{
          this.callJsonGetRestApiResponse=JSON.stringify(data);
          console.log("called from callJsonGetRestApi",data)
      });
    }

    else if(type=="callJsonDataRestApi"){
      this.callJsonDataRestApi("https://reqres.in/api/users",{name:"test",email:"test@yxyz.com"}).subscribe(data=>{
        this.callJsonDataRestApiResponse=JSON.stringify(data);
        console.log("called from callJsonDataRestApi",data)
      });
    }
    else{
      this.callFormDataRestApi("http://localhost/test.php",{name:"test",email:"test@yxyz.com"}).subscribe(data=>{
        this.callFormDataRestApiResponse=JSON.stringify(data);
        console.log("called from callFormDataRestApi",data)
      });;
    }
  }

// calling get rest api   
callJsonGetRestApi(url):Observable<any> {
   
    
    return this.http.get(url)
      .pipe(map((data: any) => {
      //handle api 200 response code here or you wanted to manipulate to response
        return data;

      }),
        catchError((error) => {    // handle error
         
          if (error.status == 404) {
            //Handle Response code here
          }
          return throwError(error);
        })
      );

  }

// calling json post rest api 

callJsonDataRestApi(url: string, form: Object) {

    

    return this.http.post(url,form)
      .pipe(map((data: any) => {
      //handle api 200 response code here or you wanted to manipulate to response
        return data;

      })
      ,
       catchError((error) => {    // handle error
         
          if (error.status == 404) {
            //Handle Response code here
          }
          return throwError(error);
        })
      );

}


// calling form data post rest api 

callFormDataRestApi(url: string, form: Object) {

  let formData = form;//{name:"test",email:"test@yxyz.com"};
  const uploadData = new FormData();
  for (let i in form) {
    if (form[i] instanceof Blob) // check is file
      uploadData.append(i, form[i], form[i].name ? form[i].name : "");
    else if (form[i] instanceof Array) { //check type of Array

      for (let arr in form[i]) {
        for (let lst in form[i][arr]) {
          if (form[i][arr][lst] instanceof Blob) { // check is file
           
            uploadData.append("" + i + "[" + arr + "][" + lst + "]", form[i][arr][lst], form[i][arr][lst].name ? form[i][arr][lst].name : "");
          }
          else {
            uploadData.append("" + i + "[" + arr + "][" + lst + "]", form[i][arr][lst]);
          }
        }
      }
    }
    else
      uploadData.append(i, form[i]);
  }
  formData = uploadData
  let headers = new HttpHeaders({
   'Authorization': 'Bearer your_token'   //add your api token for auth
  }).set('Content-Type', []);

  return this.http.post(url,formData, { headers: headers})
    .pipe(map((data: any) => {
    //handle api 200 response code here or you wanted to manipulate to response
      return data;

    })
    ,
     catchError((error) => {    // handle error
       
        if (error.status == 404) {
          //Handle Response code here
        }
        return throwError(error);
      })
    );

}  

   
}

Step 5: Open html file and start editing

In the html file, we are creating 3 buttons to call the 3 different methods and their responses.

<p>Rest-api Component</p>

<div>
    Example : calling json get request <br>
    <button (click)="onClick('callJsonGetRestApi')">Call Api </button> <br> <br>

    Response: <br><br>
    <b> {{callJsonGetRestApiResponse}}</b>
</div>

<br>

<div>
    Example : calling json post  request <br>
    <button (click)="onClick('callJsonDataRestApi')">Call Api</button> <br> <br>
    Response: <br><br>
   <b> {{callJsonDataRestApiResponse}}</b>
</div>

<br>

<div>
    Example : calling form date post request <br>
    <button (click)="onClick('callFormDataRestApi')">Call Api</button> <br> <br>
    Response: <br><br>
    <b>  {{callFormDataRestApiResponse}}</b>
</div>

<br>


Now, we have implemented component and html fileRun the code using ng serve command in terminal.

Final output screenshot:

Angular rest api request response

You can download the source code of angular and php from below link:

Leave a Reply