return 已延迟的可观察对象

return observable that is deferred

我一直遇到这个问题,我认为我的方法不是最好的,希望能得到一些帮助。

我有一个函数 return 一个 observable 直到一段时间后才可用(用户单击模态按钮、http 调用完成等)。假设我想显示一个确认模式,并根据用户的选择从函数中继续或 return。 (注意:模态 return 是一个承诺)

doWork = () => {
  openConfirm().subsribe(res => {
    if (!res) { return };   // return from function if user selects 'No'
    
    // else proceed
  });
}

这里是我认为我return使用 from

观察到的错误
openConfirm = (): Observable<any> => {

  // ng bootstrap modal asking "Would you like to proceed" with a yes or no button 
  let modalRef = this.modalService.open(ConfirmModalComponent, {});


 return from(modalRef.result.then(res => {
        return true;  // Yes button
      }, () => { 
        return false;  // No button
      }));
  }
}

我希望 Observable 等到用户在 returning 之前在模态上选择是或否。就像我的情况一样。但是有更清洁的方法吗?如果我删除 from() 运算符和 return of(true) or of(false) 我会收到无法订阅未定义的错误。

我不确定,但请尝试使用 from 运算符,就像您使用的 1.

doWork = () => {
  openConfirm().subsribe(res => {
    // promise was a success - Yes clicked
  }, err => { // error callback of subscribe
    // promise was a failure - No clicked
  });
}
.....
openConfirm = (): Observable<any> => {

  // ng bootstrap modal asking "Would you like to proceed" with a yes or no button 
  let modalRef = this.modalService.open(ConfirmModalComponent, {});


   return from(modalRef.result)
  }
}

看看您是否可以利用仅从 (Promise) 返回并订阅此 promise 的优势,看看可观察的漏斗是否正确地连接到成功回调和错误回调。