【问题标题】:Angular observable doesn't get initial valueAngular observable 没有得到初始值
【发布时间】:2019-06-15 06:17:00
【问题描述】:

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

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

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

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,但我不确定。我尝试使用ConnectableObservable 这样做,但这会导致其他问题。

【问题讨论】:

  • 尝试将new Subject&lt;boolean&gt;() 更改为new BehaviorSubject&lt;boolean&gt;(false)

标签: angular rxjs observable


【解决方案1】:

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-08-01
    • 2018-05-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-01-13
    • 2015-09-03
    • 2015-03-11
    相关资源
    最近更新 更多