Angular 6 use Async calls
Angular 6
First, you should know that in Typescript, there's two ways of making async calls : Promises and Observables.
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
- They can be stopped
- They can be played again
- They have lot of useful operators
- They can handle several values
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 :
myService.getAny().subscribe(
responseAfterSuccess => {}
responseAfterError => {}
);
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
this.myVar = myService.getAny();
Your variable
myVar
will contain an Observable. Now, in your HTML, with this<div *ngFor="let item of myVar | async"></div>
So let’s say you had the following promise-based code:
In “Observable land” this is really not any more complicated:
Comments
Post a Comment