Ashot Aleqsanyan
Ashot Aleqsanyan

Reputation: 4453

Angular async pipe usage difference

For example, if I have an Observable in my component and I want to use it in my template in multiple places or I need to put the Observable value into the child component in case of only the result is not null

my.component.ts

export class MyComponent {
   myObservable$: Observable<SomeData | null>;
}

I can do it in these different ways:

First way

<child-component *ngIf="myObservable | async as data" [data]="data"></child-component>

Second way

<child-component *ngIf="myObservable | async" [data]="myObservable | async"></child-component>

I would to know is there any performance difference or usage recommendation?

Upvotes: 0

Views: 117

Answers (2)

Roman
Roman

Reputation: 86

If you need to show some block based on your observable value, the best way to do it is the following way:

<ng-container *ngIf="myObservable | async as data">
   <child-component [data]="data"></child-component>
</ng-container>

In this case, you don't create an extra HTML-component and we get the value for our child-component.

Also, remember to avoid passing observables into the components. Components have to have values in their inputs.

Upvotes: 2

AliF50
AliF50

Reputation: 18809

The First way is the preferred way because each | async pipe is a subscription.

In the Second way you are subscribing twice and you can have a performance hit (doubt you will notice it).

Imagine your observable stream was something like this:

myObservable$ = anotherObservable$.pipe(map(complicatedStuffHere()), map(moreComplicatedStuff()));

With the 2nd way, complicatedStuffHere() and moreComplicatedStuffHere() will be called twice. Basically, each async is a new subscription and it can cause a performance hit.

Upvotes: 2

Related Questions