【问题标题】:[Angular 10][Rxjs] Why second pipe not firing[Angular 10][Rxjs] 为什么第二个管道没有触发
【发布时间】: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


【解决方案1】:

因此解决方案是将*ngFor="let label of labels$ | async"pre 移动到更高阶的ng-container

<ng-container *ngIf="vm$ | async as vm">
  <header>
    <ng-container *ngFor="let label of labels$ | async">
      <pre>
         {{label | json}} 
      </pre>
    </ng-container>
  </header>
</ng-container>

我不知道为什么,但是这样可以。也许有人可以解释一下。

【讨论】:

    猜你喜欢
    • 2012-09-22
    • 2019-08-24
    • 1970-01-01
    • 2022-10-25
    • 1970-01-01
    • 2019-02-10
    • 2020-06-18
    • 2017-03-11
    • 1970-01-01
    相关资源
    最近更新 更多