Search code examples
angularrxjsobservablebehaviorsubject

Resolve custom rxjs Subject in Angular template using async pipe


I have a custom BehaviourSubject in my Angular app, that is used as an Observable in my template.

When I call next on the Subject I expect the Subject in the template to be resolved. I use the async pipe to listen to asynchronous changes in this Subject.

I created an example in Stackblitz to show the problem that I have: https://stackblitz.com/edit/angular-kmou5e

In app.component.ts I created an example asynchronous method, that sets a value to this.data after a timeout. As soon as this.data is set, hello.component.ts is initialized and rendered. I listen to OnChangesin HelloComponent and call next() on the custom Subject within HelloComponent.

As you can see in the template of HelloComponent I expect the observed Subject customSubject$ to be rendered as an <h1> as soon as is gets a value through next().

You can see, that the subscription of the customSubject$ is called, as shown in the logs. Only the template doesn't render this Observable/Subject.

How can I get the template to render when using a custom Subject? Do I need to use a different pipe?

FYI: I also tried to assign the value of the Subject to a new Observable using combineLatest, but it didn't work as well.


Solution

  • It's a timing issue. Just change your Subject to a Behavior Subject (which caches the last emitted value) and your template will display the latest emitted value.

    enter image description here

    Here is a good resource on the various types of subjects.