等待 observable 给变量赋值,然后再尝试对其进行操作

Wait for observable to give value to variable before trying to do something with it

我有一个问题,在处理可观察对象时不断出现:

someObservable$.subscribe(response => this.ref = response);

if (this.ref) {
    // do something with this.ref value
}
ERROR: this.ref is undefined

如何在依赖于 this.ref 的 运行ning 代码之前等待订阅为 this.ref 提供值?

我假设这与时间有关,比如订阅数据库需要一定的时间才能完成读取,因为如果我将上面的代码附加到按钮点击事件,它只会执行在我点击按钮几次之后。所以理论上,我可以使用 setTimeout 等待 5 秒,然后 运行 代码。但是我想知道是否有 RXJS 运算符或其他东西可以解决这个问题。

谢谢

假设 someObservable$ 是 HTTP 请求的可观察对象,将依赖于 this.ref 的代码移动到订阅处理程序中。这是一个例子:

someObservable$.subscribe(response => {
    this.ref = response;
    // Do whatever work relies on this.ref here.
});

一旦您收到来自 HTTP 请求的响应,就会触发订阅处理程序。所以这应该是完成所需工作的时间。如果 this.ref 是模板的变量,则模板应负责使用新值自动更新视图。