将 Observables 链接到 ajax 调用的队列列表

chaining of Observables to queue list of ajax calls

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

我们有 RxJS observables 的选项吗?

当然,concat 是该工作的正确创建函数。它传递了一个 Observable 列表并按顺序完成它们,一个接一个。如果其中任何一个失败,就会发送一个错误通知,可以在 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")
)

concatdocumentation 为:

Creates an output Observable which sequentially emits all values from given Observable and then moves on to the next.

使用 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")
  );