Skip to content
Readerstacks logo Readerstacks
  • Home
  • Softwares
  • Angular
  • Php
  • Laravel
  • Flutter
Readerstacks logo
Readerstacks
call api in angular

How to call api in angular 12?

Aman Jain, September 10, 2021November 7, 2023

In this tutorial, we are going to call the rest API’s using the angular HttpClient. To fetch data from server we need to call api in angular so we can get the updated data from serve. Angular has vast features and library to call the web or rest API’s.

Step to call api in angular

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:

Screenshot 2021 09 10 at 1.40.38 PM
Angular rest api request response

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

Download Code from github

Related

Uncategorized

Post navigation

Previous post
Next post

Related Posts

Uncategorized Laravel database transactions

How to use database transaction in laravel eloquent with example ?

January 1, 2022February 22, 2024

Database Laravel Transaction in laravel eloquent are used to execute multiple or single database operations which maintainer ACID(atomicity, consistency, isolation, and durability) property of transactions. In laravel we can archive the database transaction by DB facade. Laravel DB facade provides two methods to handle the transactions one through DB::transaction() method…

Read More
Laravel Call Controller Method from Another Controller in Laravel

How to Call Controller Method from Another Controller in Laravel ?

December 2, 2023March 16, 2024

In this article we will learn Call Controller Method from Another Controller in Laravel. Sometimes we need to access the controller method from another controller to save the same code on multiple locations. Best way to achieve it is using create a separate service class or trait in PHP so…

Read More
Uncategorized Laravel ajax form with example

Submit form using jQuery in Laravel

November 18, 2021November 18, 2021

jQuery is most popular library to handle the client side events like form submit, click, change etc. In this article we will learn to submit the form using jQuery Ajax method. Ajax is mostly used when we do not want to reload the page and real time interaction. In this…

Read More

Aman Jain
Aman Jain

With years of hands-on experience in the realm of web and mobile development, they have honed their skills in various technologies, including Laravel, PHP CodeIgniter, mobile app development, web app development, Flutter, React, JavaScript, Angular, Devops and so much more. Their proficiency extends to building robust REST APIs, AWS Code scaling, and optimization, ensuring that your applications run seamlessly on the cloud.

Categories

  • Angular
  • CSS
  • Dart
  • Devops
  • Flutter
  • HTML
  • Javascript
  • jQuery
  • Laravel
  • Laravel 10
  • Laravel 11
  • Laravel 9
  • Mysql
  • Php
  • Softwares
  • Ubuntu
  • Uncategorized

Archives

  • May 2025
  • April 2025
  • October 2024
  • July 2024
  • February 2024
  • January 2024
  • December 2023
  • November 2023
  • October 2023
  • July 2023
  • March 2023
  • November 2022
  • October 2022
  • September 2022
  • August 2022
  • July 2022
  • June 2022
  • May 2022
  • April 2022
  • March 2022
  • February 2022
  • January 2022
  • December 2021
  • November 2021
  • October 2021
  • September 2021
  • August 2021
  • July 2021
  • June 2021

Recent Posts

  • Understanding High Vulnerabilities: A Deep Dive into Recent Security Concerns
  • Understanding High Vulnerabilities in Software: A Week of Insights
  • Blocking Spam Requests with LaraGuard IP: A Comprehensive Guide
  • Enhancing API Development with Laravel API Kit
  • Exploring the Future of Web Development: Insights from Milana Cap
©2023 Readerstacks | Design and Developed by Readerstacks
Go to mobile version