Rest API in Angular 4

Download Code Download From Github


I am working on Angular 4 before last few couple of months and now good command on it and each day passes with some new experiments and lots of learning. But it could not be possible in a single day but with practice of hours and day after day learning. So, I am sharing couples of things with you with Angular 4 Rest API. I will also provide an example how to use API with Angular 4.

So, now let’s ready for a deep dive for couple of minutes for learning use of Rest API with Angular 4. As we know that Angular Services provides flexibility for reusing code in our Application, with help of it we can be able to use methods and properties multiple times after adding few lines in our application. So it is good habit to define Rest APIs inside Angular services. Now for this purpose we have to need one component and one service,

Service: Contains definition of function that returns APIs result.

Component: Use result of return data from Angular service and then use return inside Angular Component.

So now let’s code for this purpose I have design an Application named RestApiTester and for this purpose I have simple write command ng new RestApiTester as I have discussed in previous lessons, after that my application is ready for further operations.

Now I am creating a component named restAPIComponent and a service named restAPIService.

Here I am creating component using angular-cli command ng g component restAPIComponent and Angular component will be created and similarly using angular cli command ng g service restAPIService for creating Angular service.

For getting data from APIs in Angular we have to add some packages inside app.module.ts HttpClientModule, HttpModule because without them we can’t be able to get result.

So At first make changes inside our app.module.ts file then we will move further. As we know that after executing angular-cli command ng g component component_name and service ng g service service_name some auto change will be occurred so after that our app.module.ts file will be look like this
app.module.ts


import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';

import { AppComponent } from './app.component';
//Import Component
import { RestApicomponentComponent } from './rest-apicomponent/rest-apicomponent.component';
//import Service
import {RestApiserviceService} from './rest-apiservice.service';

@NgModule({
  declarations: [
    AppComponent,
    RestApicomponentComponent
  ],
  imports: [
    BrowserModule
  ],
  providers: [],
  bootstrap: [AppComponent]
})
export class AppModule { }

Because we want to get result from APIs so we have to make more changes i.e. in terms of adding some packages and importing some modules and also adding routing modules inside our app.moodule.ts, So after that our code will be look like this
app.module.ts


import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { AppComponent } from './app.component';
//Import Component
import { RestApicomponentComponent } from './rest-apicomponent/rest-apicomponent.component';
//import Service
import {RestApiserviceService} from './rest-apiservice.service';
//Import RouterModule
import{RouterModule,Router} from '@angular/router';
//import HttpClientModule
import {HttpClientModule} from '@angular/common/http';

@NgModule({
  declarations: [
    AppComponent,
    RestApicomponentComponent
  ],
  imports: [
    BrowserModule,
    //import HttpClientModule
    HttpClientModule,
    //Routing pages  
    RouterModule.forRoot([
      {path:'all',component:RestApicomponentComponent}
    ])
  ], 
  //Adding Service inside Provide array
  providers: [RestApiserviceService],
  bootstrap: [AppComponent]
})
export class AppModule { }

We have made changes inside our front end and for this purpose we have to use bootstrap and finally our layout of project is looks like

root_page_Angular

For this we have to write these few lines of code inside app.component.html file

app.component.html file


<div style="margin:10px;">
  <div class="container">
    <h2 class="text-center">Rest API Testing Example</h2>
    <nav class="nav nav-pills flex-column flex-sm-row">
      <a class="flex-sm-fill text-sm-center nav-link active" [routerLink]="['/all']">Get All Data</a>
      <a class="flex-sm-fill text-sm-center nav-link disabled" href="#">Link</a>
      <a class="flex-sm-fill text-sm-center nav-link disabled" href="#">Link</a>
      <a class="flex-sm-fill text-sm-center nav-link disabled" href="#">Disabled</a>
    </nav>
  </div>
</div>
<router-outlet></router-outlet>

Note : We have to use routerLink on Get All Data tab for access restAPIComponent component

Because we want to result from API so, for this purpose we will have to make some changes inside our service page but before it at first view how our service page looks like before made changes.

rest-apiservice.service.ts


import { Injectable } from '@angular/core';

@Injectable()
export class RestApiserviceService {

  constructor() { }

}

Note: for getting data from API we are using a https://jsonplaceholder.typicode.com/ platform. So, moving further I will suggest you go click link and visit site.

Before calling data from API we have to make change inside our service page so that we can be able to interact with our API. After making changes inside our service page it will be looks like

rest-apiservice.service.ts


import { Injectable } from '@angular/core';
//import Http packages
import {HttpClient} from '@angular/common/http';
// import{HttpClientModule} form '@angular/http';
@Injectable()
export class RestApiserviceService {
  public allData;
  public baseUrl='https://jsonplaceholder.typicode.com/posts';
  
  constructor(public http:HttpClient) { }
  public getAllData():any{
     let allData=this.http.get(this.baseUrl);
     console.log(allData);
     return allData;
  }

}

please have a look I have opened my console for getting output and our console output page will be looked like

Angular_component_output

Yeah I got my output now my next target is to get these results in tabular form on our component html page and for this purpose I have added following lines of code on my rest-apicomponent.component page.
rest-apicomponent.component


<div class="container-fluid">
    <h5 class="text-center border">Get 100 Records </h5>
  <!-- Checking condition for data is exiting or not -->
  <div class="row" *ngIf="allData.length>0">   
  <table class="table">
    <thead class="thead-dark">
      <tr>
        <th scope="col">Id</th>
        <th scope="col">UserId</th>
        <th scope="col">Title</th>
        <th scope="col">Body</th>
      </tr>
    </thead>
    <tbody>  
    <!--Loop for getting data inside row --> 
    <tr *ngFor="let postData of allData">
      <td>{{postData.id}}</td>
      <td>{{postData.userId}}</td>
      <td>{{postData.title}}</td>
      <td>{{postData.body}}</td>
    </tr>
    </tbody>
  </table>
</div>
</div>

Go For Live Demo

Leave a Reply

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