Is there any advantage or benefit to using a async binding vs just mapping to a concrete object when my service call returns with data for my HTML page?
Here is an example of the two options.
// component
event: any;
// ngOnInit()
this.eventService.getEvent(this.id).pipe(take(1)).subscribe(response => {
this.event = response;
}, error => {
console.log(error);
});
// service
getEvent(id: number): Observable<any> {
return this.http.get<any>(this.baseUrl + 'events/' + id);
}
<div>{{event.title}}</div>
<div>{{event.date}}</div>
// component
event$: Observable<any> = of (undefined);
// ngOnInit
this.event$ = this.eventService.getEvent(this.id).pipe(take(1),
catchError(error => {
console.log(error);
return throwError(error);
}));
// service
getEvent(id: number): Observable<any> {
return this.http.get<any>(this.baseUrl + 'events/' + id);
}
<div>{{(event$ | async).title}}</div>
<div>{{(event$ | async).date}}</div>
Async Pipe Method
The async pipe subscribes to an Observable or Promise and returns the latest value it has emitted. When a new value is emitted, the async pipe marks the component to be checked for changes. When the component gets destroyed, the async pipe unsubscribes automatically to avoid potential memory leaks. When the reference of the expression changes, the async pipe automatically unsubscribes from the old Observable or Promise and subscribes to the new one.
We use this design when we are using Onpush change detection strategy with state management library because change detection works when we get a brand new object.
It automatically subscribes and unsubscribes the observable or promise on component destruction.
cleaner and more readable as you can have numbers of async subs in the view.
Subscribe method
Here you have to unsubscribe manually, using take will unsubscribe the observable, but what if you need more data from that observable (it limits the data stream).
The major advantage for this method is you can run your logic when you receive data and can use that data at multiple places in the component.
We have used both the patterns based on the scenarios which suits well for specific situation.
Note: async pipe method needs to get a new reference of the data object passed to it in order to run the change detection and update the view.