How to Consume An API In Angular 6

Before starting this Article i assume that you are having basic latest Angular Project setup .  Let me list out the steps if consuming An API:
1. Import HttpClientModule : 

This is first step of using Http service in Angular . We have to import the HttpClientModule in the imports section  in app.module.ts . After that we need to add this to the Imports section in NgModule (please refer the image attached ).

2. Create A Common Service :
(my service name is PersonService) .
lets create a common service with to consume API web service . In my case i have create a service called  PersonService .

3. Import HttpClient in Common service :

Lets create import HttpClient in common service .

4. Create local reference for HttpClient in Common Service .

Create a local reference for the HttpClient inside the constructor .
5. Create a function which triggers the API in common service .

In PersonService i have created a method to call the API web service .

6. Add the Common service in to the component.

7. Create a local Reference for the  Common Service inside the constructor .
9. Invoke the service inside the initialization (ngOnInit) , and subscribe for the response .

After receiving the data from the web service assign it any variable which binded to the Html page . 



Comments