Introduction

In our previous article we did setup a basic Angular 10 project using angular-cli. In this article we will be using HTTPClient module in angular to integrate our UI with API. To render our data in html we will be using *ngFor.

Assumption

This article assumes you have basic understanding of JavaScript and HTML. Also you have setup basic angular project using angular-cli. If you have not yet setup this, you can read my article here.

Let's get Started

Open your angular project in vscode. If you are continuing my earlier project than the name of the project should be firstangular10app. Once you open this project navigate  src -> app -> app.module.ts add httpClientModule to imports section inside @ngModule.

You will have to add two lines, one for importing module and second for making httpclient part of package. This is how new changes should look like

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

import { AppRoutingModule } from './app-routing.module';
import { AppComponent } from './app.component';
import { HttpClientModule } from '@angular/common/http'; // newly added

@NgModule({
  declarations: [
    AppComponent
  ],
  imports: [
    BrowserModule,
    AppRoutingModule,
    HttpClientModule                                     // newly added
  ],
  providers: [],
  bootstrap: [AppComponent]
})
export class AppModule { }

Ok now we have added httpClientModule to our package. Let us now add a service which will make a call to API and fetch data before we render it. Open terminal window in vscode or command prompt and type

ng g s apiManager

Above command comes from angular-cli,

  • ng = angular-cli
  • g = generate
  • s = service
  • apiManager = Name of the service which we wish to create.

After successful execution of above command we should be able to see two new file added inside src -> app folder. We can ignore spec.ts file which is required when we write our unit test code. Now open app-manager.service.ts file and add HttpClient to its constructor. We will also have to add httpClient reference from @angular/common/http. Your code should look something like this now.

import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http'; // newly added 

@Injectable({
  providedIn: 'root'
})
export class ApiManagerService {
  constructor(private http : HttpClient) { // newly added 

  }
}

For this sample application we will be using api which are available at typicode.com. We will be specifically using https://jsonplaceholder.typicode.com/albums which return array list. Since we are using typescript let us define a model which is returned by this API. Go back to terminal / command prompt and type

ng g i ialbum
  • ng = angular-cli
  • g = generate
  • i = interface
  • ialbum= Name of the interface which we wish to create.

A new file should be create at src -> app with name ialbum.ts. Open this file and add our required attributes / properties. After change your file should look like this

export interface Ialbum {
    userId : number; // newly added 
    id : number;     // newly added 
    title : string   // newly added 
}

Now get back to api-manager.service.ts and add a function with name getAlbums() which returns Observable of Ialbum array. Your code should look something like this.

import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http'; 
import { Observable } from 'rxjs';
import {Ialbum} from './ialbum'; // newly added 

@Injectable({
  providedIn: 'root'
})
export class ApiManagerService {
  constructor(private http : HttpClient) { 

  }

  getAlbums(): Observable<Ialbum[]>{              // newly added           
    return this.http.get<Ialbum[]>("https://jsonplaceholder.typicode.com/albums");  // newly added 
  }                                               // newly added 
}

It is time to integrate this service to UI, open app.component.ts which should be available inside src -> app, add the service to constructor and use implements OnInit. Your code should now look like this.

import { Component, OnInit } from '@angular/core';
import { ApiManagerService } from './api-manager.service';
import { Ialbum } from './ialbum';                  //newly added

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.scss']
})
export class AppComponent implements OnInit {       //newly added

  albums : Ialbum[] = <Ialbum[]>[];                  //newly added
  constructor(private service : ApiManagerService){  //newly added

  }
 
  ngOnInit(){                                        //newly added
    this.service.getAlbums().subscribe((resp)=>{     //newly added
      this.albums = resp;                            //newly added
    });                                              //newly added
  }                                                  //newly added
}

In ngOnInit , we are making call to getAlbums function which we just created in our service file. Time to update our HTML temple associate with app.component.ts with data. Open app.component.html available inside src -> app and replace html tag with below.

<section>
  <table>
    <tr><th>Id</th><th>User Id</th><th>Album</th></tr>
    <tr *ngFor="let album of albums"><td>{{album.id}}</td><td>{{album.userId}}</td><td>{{album.title}}</td></tr>
  </table>
</section>

That's it we are done with our changes. Open command prompt / terminal inside vscode and type following command to compile and render our application.

ng serve -o

Now you should see albums data getting rendered at http://localhost:4200;

You can download source code from here