Rxjs share() operator with Behavior subject and async pipe - Angular

余生长醉 提交于 2019-12-05 15:28:47

This is a correct behavior. The share() operator keeps only one subscription to its parent and BehaviorSubject emits its value only on subscription.

This means that when you use the first {{testForStack$ | async}} it subscribes at the end of the chain to share() which subscribes to its parents which results in subscribing to the source BehaviorSubject that emits its value immediately.

However, the second and all consecutive {{testForStack$ | async}} subscribe to share() which already has subscribed to its parent and won't make any more subscriptions so there's nothing to push the source value to these observers.

An easy solution could be using shareReplay(1) (depending on your RxJS version) you should probably use publishReplay(1).refCount() instead because of these issues (or its pipable equivalents):

Don't use the share operator. Instead do something like this:

<ng-container *ngIf="testForStack$ | async as testForStack">

  Sub1: {{ testForStack }}
  Sub2: {{ testForStack }} 
  Sub3: {{ testForStack }}

</ng-container>

There are various other ways, for example you could use the same approach with a template using ngTemplateOutlet if you don't like use of the *ngIf. This approach allows you to create an alias variable in the same manner:

<ng-template let-testForStack [ngTemplateOutletContext]="{ $implicit: testForStack$ | async }" [ngTemplateOutlet]="selfie" #selfie>

  Sub1: {{ testForStack }}
  Sub2: {{ testForStack }} 
  Sub3: {{ testForStack }}

</ng-template>

This ng-template code is self-referencing (which is valid) and wholly untested but "should" work and avoids use of *ngIf

Read more here: https://nitayneeman.com/posts/using-single-subscription-for-multiple-async-pipes-in-angular/

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!