This angular article addresses the following topics:
- How to create angular application
- How to create angular service
- How to integrate external API with angular service
- How to create angular component
- How to integrate angular service with angular component
- How to show the API result on angular component
- How to integrate one component to the another component
- How to run the application
Prerequisite:
Following things will be installed upfront before heading to implement API integration. If not installed then please visit here
- NPM
- Node.js
- Angular-cli
- Angular 2+
- Internet Connection to download the package
- A external rest API to integrate
To integrate an external API with angular service, I will create a new angular project named “APIIntegration”. To create angular project, service and component, I will use angular-cli command which very handy.
How to create angular application
Open terminal/command prompt and type below angular-cli command
command: ng new <projectname> (Reference: https://angular.io/cli/new)
$ng new APIIntegration

This will take a while to create the project and download all required package from internet.
Once project is created, I will make sure that project is created in good shape by starting.
command: cd <projectname>
command: ng serve (Ref: https://angular.io/cli/serve)
$cd APIIntegration
$ng serve

Once is application started then it will be available on https://localhost:4200/. If it renders correctly in the browser then it’s done successfully. Now we are ready to create our first angular service.
How to create angular service
To create any feature service in angular, it’s advice to have a baseService which has common response and error handling. In this practice, I will create first baseService and then UserService will be created to get the list of users.
command: ng g s <serviceName> (Ref: https://angular.io/cli/generate#service)
$ng g s base

In above command, g=> generate, s=>service and base is service name. Angular-cli will append the Service to the given servicename. It wont create any directory structure if you want to create a service on the dedicate path then use below command.
command: ng g s <dir_path>/base
$ng g s common/base
Using above command, BaseService will be created under common directory inside the app directory of the project
I will add few common methods in baseService.
Click Here Source code of BaseService
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 |
import { Injectable } from '@angular/core'; import {Http,Response, Headers} from '@angular/http'; import {Observable} from 'rxjs/Rx'; @Injectable({ providedIn: 'root' }) export class BaseService { constructor(private http: Http) { } /* This method is used to add header properties to each request */ createHeader() { var headers = new Headers(); headers.append('Content-Type', 'application/json'); headers.append('timestamp', new Date().toISOString()); return headers; } /* This method is used to hit the provided API url */ get(url):Observable<Response>{ return this.http.get(url,{headers: this.createHeader()}).map(this.extractData).catch(this.handleError); } /* This method is used to get the good response from API */ extractData(response:Response){ return response.json(); } /* This method is used to handle the error on API response */ handleError(error:Response){ return Observable.throw(error.json()); } } |
Method | Description |
get(url) | This method accepts external API url and make http get request. |
createHeader() | This method adds some header properties to all the request if required. |
extractData(response) | This method is to handle the good response from RestAPI and extract the json data. |
handleError(error) | This method is to handle error response from Rest API. |
BaseService class will handle response and error handling in common way for rest of the angular service classes. To use http functionality in angular, HttpModule must be activated in app.module.ts. I have added one import for HttpModule and added in @NgModule imports array. This is a common way to activate any angular Module in angular application.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 |
import { BrowserModule } from '@angular/platform-browser'; import { NgModule } from '@angular/core'; import { HttpModule} from '@angular/http'; import { AppComponent } from './app.component'; import { UserListComponent } from './user/user-list/user-list.component'; @NgModule({ declarations: [ AppComponent, UserListComponent ], imports: [ BrowserModule, HttpModule ], providers: [], bootstrap: [AppComponent] }) export class AppModule { } |
How to integrate external API with angular service
Now, I will create a UserService and integrate with External API and BaseService.
1 |
$ng g s user/user |

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
import { Injectable } from '@angular/core'; import { BaseService } from './../base.service'; @Injectable({ providedIn: 'root' }) export class UserService { constructor(private baseService:BaseService) { } getUsers(){ var url = "https://reqres.in/api/users"; return this.baseService.get(url); } } |
In above UserService, I have created a method getUsers() which is integrated with external URL(https://reqres.in/api/users) of Rest API to return the list of users. I used BaseService to call http get() method which is already integrated with angular HttpModule to make http get request.
Now, UserService is ready to integrate with angular component to show the received data from Rest API.
How to create angular component
Command: ng g c <componentName> (Ref: https://angular.io/cli/generate#component )
1 |
ng g c user/userList |

In this example, I will edit user-list.component.ts and user-list.component.html to intergrate with angular UserService by getUsers() method.
How to integrate angular service with angular component
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 |
import { Component, OnInit } from '@angular/core'; import { UserService } from './../user.service'; @Component({ selector: 'app-user-list', templateUrl: './user-list.component.html', styleUrls: ['./user-list.component.css'], providers: [UserService] }) export class UserListComponent implements OnInit { users=[]; error; constructor(private userService:UserService) { this.getUsers(); } ngOnInit() { } getUsers(){ return this.userService.getUsers().subscribe(response=>this.handleData(response),error=>this.error=error) } handleData(response){ this.users = response.data; } } |
In the above component class, I imported UserService class and injected in the constructor of the component class and initialize an object to use that further in the component.
I created a getUsers() method and subscribe the userService getUsers() method. In the angular Observable subscribe method has three parameter (1) Response data, (2) Error Handling (3) completion of the method.
To handle the response data, I have created a handleData(response) method to extract certain data from external API response data. and assign the API error data to an error variable of the component.
How to show the API result on angular component
Once the data is extracted then I will show that data on user-list.component.html
1 2 3 4 5 6 7 |
<p> user-list API Integration works! </p> <ul> <li *ngFor="let user of users"> {{ user.email }}</li> </ul> |
I have all the user’s list as users. In above html code, I will traverse users list by angular *ngFor loop and print only user’s email. ‘{{}}’ is angular way to print the value of the variable in html
As I didn’t setup routing for each component because of simplicity. I will cover routing in the different blog.
How to integrate one component to the another component
I will inject user-list component in app.component.html to show all the users email as list.
1 |
<app-user-list></app-user-list> |
How to run the application
Now, I am ready to run the application again using ng serve. After navigating https://localhost:4200/


Complete Source code is available on github.com. click here
External API: https://reqres.in/api/users
Users Data:
{
“page”:1,
“per_page”:3,
“total”:12,
“total_pages”:4,
“data”:[
{
“id”:1,
“email”:”george.bluth@reqres.in”,
“first_name”:”George”,
“last_name”:”Bluth”,
“avatar”:”https://s3.amazonaws.com/uifaces/faces/twitter/calebogden/128.jpg”
},
{
“id”:2,
“email”:”janet.weaver@reqres.in”,
“first_name”:”Janet”,
“last_name”:”Weaver”,
“avatar”:”https://s3.amazonaws.com/uifaces/faces/twitter/josephstein/128.jpg”
},
{
“id”:3,
“email”:”emma.wong@reqres.in”,
“first_name”:”Emma”,
“last_name”:”Wong”,
“avatar”:”https://s3.amazonaws.com/uifaces/faces/twitter/olegpogodaev/128.jpg”
}
]
}
Happy Learning π π π