首页 > 解决方案 > Angular observable 没有得到初始值

问题描述

我的屏幕上有三个组件,其中一个是从数据库中提取的列表。两人等待列表加载。用户可以在其他两个组件之间切换,列表不需要重新加载。

我正在使用一项服务来告诉这两个组件列表已完成加载。

当列表完成时,将显示当前查看的组件。但是,如果用户在列表加载后切换视图,则新视图仍在等待可观察对象触发。

editor.service.ts:

...
private setBusReady = new Subject<boolean>();
...
getBusReady = this.setBusReady.asObservable();
...
busReady(values: boolean = false) {
  this.setBusReady.next(values);
}

list.component.ts(加载后将 busReady 设置为 true)

...
this.editorService.busReady(true);
...

viewer.component.ts(订阅并等待列表)

...
ngOnInit() {
  ...
    this.editorService.getBusReady
    .pipe(
      takeUntil(this.unsubscribe)
    )
    .subscribe(res => {
      if (res) {
        this.loading = !res;
      }
    });
  ...
}
...

带有订阅的视图在加载时没有问题,但在切换时会出现问题。我想我需要切换到一个热门的 observable,但我不确定。我尝试使用 a 来执行此操作,ConnectableObservable但这会导致其他问题。

标签: angularrxjsobservable

解决方案


我认为您应该使用BehaviourSubject,因为Subject 在您订阅时不保存当前值,它只会在 .next (仅加载数据的那一刻)触发,另一方面BehaviourSubject可以保存一个先前的值和所有即将到来的


推荐阅读