How To Consume External API In Angular 2 And Above

Hi, I am going to use two technologies to consume external API in angular 2.

  1. Observable
  2. Promise

We will also go through with the functionality of these two.

So let’s suppose a scenario-

we have given an API which has a list of students.

And we would fetch data from that API and display it on our page.

Let’s start…

To create an angular 2 project use angular CLI commands(I am assuming that you guys are already familiar with angular CLI 🙂 )

Run below command in terminal or command prompt

It will take some time to create this project for you. once it got completed go to project by

and run

when you get “Compiled successfully” message in the command line, open localhost:4200 in your browser and you will get angular’s default page.

Now start with creating a component student using CLI command. for this use below command

Above command will create four below files for you

  1. student.component.html
  2. student.component.spec.ts
  3. student.component.ts
  4. student.component.css

Apart from above this command also make an entry in app.module for the above component.

Now create a service that fetches data. To create service run command

Above command will create service and make an entry in the app.module.ts file also.

Make sure your provider in app.module must have an entry for this service. By this, your service made available at the root level.

Now create a JSON file that has data of student. (just to create fake API)

I have created a simple student.json

Place this JSON file the in assets folder. You can place it anywhere.

Create an interface to give a type for student data.

http service exists in HttpModule so to use this service you need to make below changes in app.module.ts.

import HttpModule.

Now in @NgModule decorator include HttpModule in imports array.

Your service file(StudentService) look like below –

Above service has a method getStudentList();. Inside this service, we have made a request to API through http.

Return type of this _http.get(http://localhost:4200/assets/student.json“) is Observable<Response>, but what we need Observable<Istudent[]>. To convert Observable[Response] to Observable<Istudent[]>, RxJS provide map operator. So map operator get the response and typecast it into Observable<Istudent[]>

If the hit to API gets failed then catch will handle the error.

Now to come to student.component.ts

Now import student.service in your component.

Constructor(private _studentService: StudentService) provide you an instance of this service. And I called getStudentList method of service from ngOnInit. this method return observable of <Istudent[]>. Observable transmit data as a stream. So you need to observe the observable. For this, you have to use subscribe. By using subscriber whatever data observable emit you will get.

We can see from below that subscriber have three parameter-

These three parameter represent three callback function.

next => When observable emits the data. That data passed as a parameter to this method.

error => When error occurred.

Complete => When all the data got emitted.

 

To show data I am using below HTML file.

That is the simplest way to get data through observable.

What happened if an error occurs:

To handle an error, RxJS provide catch operator.

To use catch import catch class

You can see into service that we have chained the method catch in http.get(). Inside this method, another method handleError called.

Type of error is Response. You need to throw this error back to component. We have to use Observable.throw method for this.

On the component side, we have subscribed that have one callback function that called when an error occurred using that method we can get the error and show any meaning full message to end user.

Now What if you hit the API and get error, but you want to keep retrying for 2 or 3 time

For this RxJS provide retry method.

retry(): To use retry method you need to import retry

In above function, if getStudentList() throw an error retry method will subscribe again and make another call to api. And it will retry 5 times. But it tries all the attempt immediately one after another. That would not be useful.

retryWhen();

With the help of retryWhen(), when We get an error we can delay next request by some amount of time.

So now we want if the request fails next request would be made after 1 second and when the total number of request exceeded by 5 it stops.

To achieve this we have to import retryWhen, scan and delay

In below function retryWhen trigger when an error occurred. And on that error scan function called. This scan has two parameter first is a function and the second is the seed that is to initialize. So for the first parameter, I am using to track the number of attempts and set the value of seed to 1. Now if a request fails, retryWhen make another request after one second and when the number of attempts is greater than five it throws an error.

How to Unsubscribe?

To unsubscribe request RxJS provide a method unsubscribe();. Unsubscribe is a method of interface ISubscription. To use the unsubscribe method you need to import

 

Now take a class variable of type ISubscription.

In below code, I have unsubscribed the observable when the number of attempts is equal to 3.

That was all about observable.

Now I am going to use promise for same.

To use promise first need to import

http.get() return observable, so we need to return promise we will use toPromise() to transform observable to promise.

And I have removed Observable.throw(error) as we are not using Observable any more.

Once we made above changes in service we will start getting an error on component side that subscriber does not exist in promise.

Promise provides a method then. And then have two methods

onfullfilled=> When request completed successfully.

onrejected => When request rejected.

Promise And Observable

Promise emits single value, Observable emits a stream of data over a period of time.

Promise has two methods onfullfilled and onrejected, called on request completed and rejected respectively. While Observable have three methods onnext for each value emit, onerror when request failed and oncomplete when last data emitted.

Promise is not lazy, Observable is. If you do not subscribe the observable, It is not going to make any request, but Promise always makes request irrespective of whether you are using the method or not.

Promise cannot be canceled while Observable can be. Apart from this Observable provide retry(), retryWhen() method that promise doesn’t have.

 

This wall all about Promise and Observable

You can get the code of above project from below link-

https://github.com/visheshmishra/ObservaleVsPromise

 

Also, check our blog Angular Vs React Vs Vue >>

Please follow and like us:
20

Leave a Reply