Using the async pipe makes handling subscriptions much easier. It automatically handles unsubscribing unlike subscribing in the component.
That said, there is a better pattern than what the example is showing. Rather than having multiple async calls on components, you can write it 2 different ways. I’m assuming these components are in the same template file:
<div *ngIf="(myObservable$ | async) as myObservable">
<my-random-component [id]="myObservable.id">
<my-random-component2 [name]="myObservable.name">
</div>
Wrapping the code in ngIf
does 2 things:
- It cuts down on duplicate code
- The components do not exist until
myObservable$
is ready
There’s also one more idea if you want to stick with calling async every single time:
// COMPONENT
name$: Observable<string>;
id$: Observable<string>;
ngOnInit() {
// Return the exact value you want rather than the full object
this.name$ = OBSERVABLE_SOURCE
.pipe(
map(res => res.name)
);
this.id$ = OBSERVABLE_SOURCE
.pipe(
map(res => res.id)
);
}
// TEMPLATE
<my-random-component [id]="(id$ | async)">
<my-random-component2 [name]="(name$ | async)">
Pipes do not automatically run without a subscription. You can map, tap, or do anything else you want with it and it will not run until you add async/.subscribe()
.