【发布时间】:2021-02-11 20:34:52
【问题描述】:
我有两个订阅者订阅同一个 Observable,但第二个订阅者没有发出值。 管道是否存在我不了解的限制?
component.ts
private readonly destroyed$ = new Subject<void>();
public readonly vm$ = this.service.vm$.pipe(
tap(console.log),
takeUntil(this.destroyed$)
);
public readonly labels$ = this.service.vm$.pipe(
zip(this.makeLabels),
tap(console.log),
takeUntil(this.destroyed$)
)
...
constructor(private readonly service: SomeService) {
this.service.load();
}
ngOnDestroy(): void {
this.destroyed$.next();
this.destroyed$.complete();
}
some.service.ts
export class SomeService implements OnDestroy {
private readonly destroyed$ = new Subject<void>();
private _vm$ = new BehaviorSubject<ViewModel>(null);
public readonly vm$ = this._vm$.asObservable().pipe(takeUntil(this.destroyed$));
...
load() { this._vm$.next({...}) }
}
component.html
<ng-container *ngIf="vm$ | async as vm">
<header>
<pre *ngFor="let label of labels$ | async">
{{label | json}}
</pre>
</header>
</ng-container>
【问题讨论】:
-
你不能把
vm$和label$结合起来,这样你就只能管道/订阅一次吗?或者这是一个普遍的问题,这是否可能? -
您在此处分配
_vm$的实际值是多少:load() { this._vm$.next({...}) }? -
这更像是一个一般性问题,因为这样我可以使我的工作代码更具可读性。
-
zip的意图是什么,这可能会导致您无法按预期发射。 -
可观察的发射和对象,我需要组成一个新对象。基于documentation,我认为这是我应该用于这个 puprose 的那个,但我可能错了。
标签: angular typescript rxjs