【问题标题】:chaining of Observables to queue list of ajax calls将 Observables 链接到 ajax 调用的队列列表
【发布时间】:2018-12-16 17:59:03
【问题描述】:

我有一个动态的 Ajax URL 数组,并试图按顺序排列调用。成功完成第一次调用后,将进行第二次 ajax 调用,如果结果失败则结束执行循环。就像那样,它应该完成数组直到结束。

对于 RxJS 的 observables,我们有这个选项吗?

【问题讨论】:

    标签: javascript asynchronous rxjs angular2-observables


    【解决方案1】:

    使用concatMap 顺序获取数据但使用mergeMap 异步处理的示例。

    Codexample at codesandbox.io

    import { from } from "rxjs";
    import { concatMap, map, catchError, tap, mergeMap } from "rxjs/operators";
    
    const urls = [
      "https://randomuser.me/api/",
      "https://geek-jokes.sameerkumar.website/api",
      "https://dog.ceo/api/breeds/image/random"
    ];
    
    from(urls)
      .pipe(
        concatMap(url => {
          console.log("=>Fetch data from url", url);
          return fetch(url);
        }),
        tap(response => console.log("=<Got reponse for", response.url)),
        mergeMap(response => response.json()),
        tap(data => console.log("Decoded response", data))
      )
      .subscribe(
        () => console.log("fetched and decoded"),
        e => console.log("Error", e),
        () => console.log("Done")
      );
    

    【讨论】:

      【解决方案2】:

      当然,concat 是该工作的正确创建函数。它传递一个 Observables 列表并按顺序完成它们,一个接一个。如果其中任何一个失败,则会发送一个错误通知,该通知可以在subscribe 函数中处理。该链在出错后立即完成,防止触发后续的 Ajax 调用。

      一个例子可能如下所示:

      concat(...urls.map(
          url => this.http.get(url))
      ).subscribe(
          next => console.log("An Ajax call has finished"),
          error => console.log("An Ajax call has gone wrong :-( "),
          complete => console.log("Done with all Ajax calls")
      )
      

      documentation 对应 concat 的内容如下:

      创建一个输出 Observable,它依次从给定的 Observable 发出所有值,然后继续下一个。

      【讨论】:

      • 谢谢,似乎是一个简单的解决方案,你能帮忙提供一个工作模型吗?非常感谢。
      猜你喜欢
      • 2017-12-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-01-04
      • 2019-03-18
      • 2023-03-20
      相关资源
      最近更新 更多