【问题标题】:How to wait for function with observable to resolve?如何等待 observable 函数解析?
【发布时间】:2023-01-14 09:17:41
【问题描述】:

在 Angular/Angular2 上工作,我得到了类似的东西

buildData() {
this.services.getData()).pipe(takeUntil(this.ngUnsubscribe))
    .subscribe(response => {
        this.handleResponse(response);
})


handleEvent($event) {
const value = this.value;
this.buildData();
//Do some stuff here after buildData is finished. 
}

我不知道的是如何等到 buildData() 完成。

我尝试添加等待

handleEvent($event) {
const value = this.value;
await this.buildData();
//Do some stuff here after buildData is finished. 
}

但它不起作用,因为它不返回承诺。

【问题讨论】:

  • rxjs 通常需要转向反应式代码而不是命令式代码。因此,一个可行但可能不好的答案是不订阅,返回可观察对象,使用自来水管道运算符调用 handleResponse 作为副作用,并在 handleEvent 中执行 this.buildData().subscribe((data)=> {do some stuff})。需要handleResponse的详细信息以及做一些事情虽然是适当的建议
  • 请注意,与 Promises 不同,Observable 可以随时间发出多个值

标签: javascript angular rxjs angular2-observables rxjs-observables


【解决方案1】:

我建议您使用带有 tap 运算符的管道来触发副作用,然后返回可观察对象,以便稍后订阅它或从中触发其他副作用

buildData() {
  return this.services.getData()).pipe(takeUntil(this.ngUnsubscribe))
    .pipe(
      tap((data) => this.handleResponse(response))
    );
})


handleEvent($event) {
  const value = this.value;
  this.buildData()
    .pipe(
      //your operations
    ).subscribe();
}

【讨论】:

    猜你喜欢
    • 2023-04-03
    • 1970-01-01
    • 1970-01-01
    • 2021-07-26
    • 1970-01-01
    • 1970-01-01
    • 2019-07-24
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多