I have been googling for a few days and found many different scenarios about how to use Async API calls with Angular 5 ( or 2-3-4, whatever ).
Can anyone give me some correct example ( some good use-case ) about it?
ex.
- making an API call using ( async - try - catch )
- how to 'subscribe' to that call in a Component level
Thank You !
I will give you an asnwer based on my opinion and how I learnt. So don't take it for the absolute truth, but rather question it !
First, you should know that in Typescript, there's two ways of making async calls : Promises and Observables.
Promises are native in ES6, Observables are part of Rx JS.
But which one to use ?
Since it's my opinion, I will tell you to use Observables, because
All of this, Promises can't do.
Making an API call
Import the module
Very simple : first, you need to import the module responsible for that :
This is the new and improved http service in Angular 5. I highly recommend you to use it, since the older one (
Http
) will soon be obsolete.Use the HttpClient service
Now, in your services, you can use the
HttpClient
like soUse the business service
In your component, you can now do
Complementary information
Handling errors or loaders
Say you want to show a progress bar, or handle errors : to do that, you will have to use Interceptors. Interceptors are services that will catch your request before (or after) sending it, and will do something.
Here is a simple interceptor for errors :
To use it, simply provide it with your value in your module :
I think you guessed, but you can use it to handle progress bars also ;)
Subscribing to an Observable and using async
As you've seen before, you can subscribe to an http call.
If you want to handle specific errors and do some logic in your component, here is how :
With this code, you will handle the success and the error.
Last thing, the async pipe : the async pipe transforms an Observable into data. To use it, do so
Your variable
myVar
will contain an Observable. Now, in your HTML, with thisAngular will wiat for data to arrive before displaying anything, and will transform the Observable into data, as if you did it by hand.