External API Integration with Angular 2+ service and component

Angular Logo

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 image has an empty alt attribute; its file name is create_new_prj.jpg

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

This image has an empty alt attribute; its file name is start_the_application-1024x271.jpg

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

This image has an empty alt attribute; its file name is create_base_service.jpg

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

MethodDescription
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.

How to integrate external API with angular service

Now, I will create a UserService and integrate with External API and BaseService.

UserService create command in user directory under app directory

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 )

userList component is created with a directory named as <componentName> but it will add ‘-‘ and lowercase for camel case component e.g. userList => user-list directory will be created.
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

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

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.

How to run the application

Now, I am ready to run the application again using ng serve. After navigating https://localhost:4200/

Console output after start the application
This the final rendering of the angular application

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 πŸ™‚ πŸ™‚ πŸ™‚

share or like this post
Share

Leave a Reply

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

Share