Async Pipe all the things!. Quick tutorial of how you can easily… | by joaquin cid | Medium
Never .subscribe() again, | async instead
When dealing with Observables in Angular we need to subscribe to them to unwrap the data stream and do what we need to do with each emitted value.
The most common way to this is to:
data: Person[]ngOnInit(){
this.service.data$.subscribe(data=>{
this.data = data
})
}
And on our template:
<p *ngFor="let item of data">item.name<p>
This pattern requires you to remember to unsubscribe
on the ngOnDestroy
event to avoid memory leaks and undesired behavior on your app.
You can simplify this by using the async
pipe, here’s how it looks like now:
data$: Observable<Person[]>ngOnInit(){
this.data$ = this.service.data$
}
And the template:
<p *ngFor="let item of data$ | async">item.name<p>
Now, the | async
is subscribing for us on the template and not only it does that, ¡it automatically unsubscribes for us on the ngOnDestroy
event!
How async pipe works
async
pipe receives the Observable we define on the template, subscribes to it, and every time it receives a new emission of data it triggers the ChangeDetection cycle to update the view accordingly.
More important, async
pipe implements the ngOnDestroy
event and unsubscribes from your observable.
You can take a look that the source code here:
Goodbye .unsubscribe()
So now that we know this we can kiss .unsubscribe()
goodbye!
If you are wondering how to subscribe to an Observable that you don’t actually want to display data on the template or it doesn’t stream any data, here’s how you can do it.
Let’s consider a FormGroup
to which we want to perform an operation every time its value changes.
form: FormGroup({
...
})valueChanges$: Observable<any>ngOnInit(){
this.valueChanges$ = this.form.valueChanges.pipe(
tap(value=>{
... do something here
})
)
}
Instead of subscribing to it, we can | async
to it inside an ng-container
. This way we wont need to subscribe and unsubscribe to the Observable without also displaying any data in the page.
<ng-container *ngIf="valueChanges$ | async"></ng-container>
Conclusion
We’ve learned how to use the async pipe to subscribe to any Observable on Angular, and how this eliminates the need to unsubscribe from it.
Không có nhận xét nào:
Đăng nhận xét