0

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?

2 Answers 2

2

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.

Sign up to request clarification or add additional context in comments.

3 Comments

thank you AliF50 for your answer, but I think you are not right about the second way, it will be called only once and will notify both listeners
let me create a simple reproduction example so we can test what you said.
ah yes, you are right, it will be called twice, stackblitz.com/edit/rxjs-mncsxk?file=index.ts here is the reproduction example if you will need, thank you!
2

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.

1 Comment

Roman Thank you for your answer. yeah you are right, I will be careful

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.