【问题标题】:Wait for an API call to complete without using toPromise() rxjs operator等待 API 调用完成而不使用 toPromise() rxjs 运算符
【发布时间】:2022-01-09 16:23:45
【问题描述】:

我在我的应用程序中使用了几个 API。虽然有些 API 调用是相互关联的。我想确保之前的 API 调用已经完成。我目前正在使用.toPromise()方法来处理这个场景。

除了将 Observable 转换为 Promise 之外,您还建议 哪些其他替代方法?

【问题讨论】:

    标签: angular typescript api rxjs


    【解决方案1】:

    您根本不需要将 Observable 转换为 Promise。

    您可以使用 submit 方法触发 Observable 的执行,您可以使用 concatMap 运算符连接多个 Observable 的执行。

    因此,例如,如果您有 3 个 API 想要一个接一个地执行,并且您需要将前一个 API 的结果用作后续 API 中的参数,您可以使用类似这样的代码

    api_1() // returns an Observable
    .pipe(
       concatMap(result_1 => {
         return api_2(result_1)  // api_2 returns an Observable
       }),
       concatMap(result_2 => {
         return api_3(result_2)  // api_2 returns an Observable
       }) 
    )
    .subscribe({  // subscribe triggers the execution
       next: result_3 => {// do something with result_3},
       error: err => {// handle the error condition},
       complete: () => {// do something, if you need, when the Observable completes}
    })
    

    作为参数传递给subscribe方法的对象是观察者。

    您可以在this article 中阅读有关如何通过 API 使用 Observables 的更多详细信息

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-03-09
      • 2022-01-13
      • 1970-01-01
      • 2019-03-25
      • 2019-11-19
      • 1970-01-01
      • 2018-06-12
      • 2012-08-27
      相关资源
      最近更新 更多