Issue
I have very simple component template:
<button (click)="emitNextValue()">Next Value</button>
<p *ngIf="text$ | async">
{{ text$ | async }}
</p>
and component code:
export class AppComponent {
count = 1;
text$ = new Subject<string>();
emitNextValue(): void {
this.text$.next(`Value ${this.count}`);
this.count += 1;
}
}
As you can see, the <p>
in the template should be displayed only if text$
Subjects emit value. Clicking the "Next Value" button will call next
on the subject and thus should show the paragraph.
The problem is that <p>
is displayed only on the second click, which I think is incorrect.
Any idea what I am missing, or this is actual bug?
Demo is available on stackblitz.
Solution
the subscription happened late. in common case you could make your subscription replay the last event by shareReplay(1)
operator or by using ReplaySubject(1)
subject. But in your particular case there is a better solution for that
<p *ngIf="text$ | async as text">
{{ text }}
</p>
ngIf allows to "store" the result of expression which is very usefull for exactly such cases
Answered By - Andrei
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.