【问题标题】:Wait for observable to give value to variable before trying to do something with it等待 observable 为变量赋值,然后再尝试对其进行操作
【发布时间】:2021-07-16 05:22:02
【问题描述】:

我遇到了一个在处理 observables 时不断弹出的问题:

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

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

在运行依赖于this.ref 的代码之前,如何等到订阅为 this.ref 提供了一个值?

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

谢谢

【问题讨论】:

    标签: typescript rxjs observable subscription


    【解决方案1】:

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

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

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2013-03-21
      • 2011-01-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-02-12
      • 1970-01-01
      相关资源
      最近更新 更多