【问题标题】:rxjs sequential dynamic number of api callsrxjs 连续动态数量的 api 调用
【发布时间】:2021-01-12 03:45:49
【问题描述】:

尝试创建将执行以下操作的 rxjs 管道: 本质上,我有一个动态数量的 API 调用数组。每次我需要进行新的 API 调用时,我都会将其推送到数组中。

然后,我将数组转换为 RXJS switchmap 运算符数组。 (呼叫的顺序无关紧要,只是我需要在前一个呼叫完成后拨打一个电话,而不是同时)。

最后,我尝试将 rxjs 运算符数组分布在一个管道中:

const obsArray = [randomQuote(), getCatFacts(4), recipeSearch('oil')]
const OperatorWrap = obsArray.map((obs) => {
  return rxops.switchMap((val) => { return obs })
})



const pipeline= of(1).pipe(...OperatorWrap);

但我收到一条奇怪的错误消息:

【问题讨论】:

    标签: rxjs


    【解决方案1】:

    concatAll这是你需要的

    concatAll - 收集 observables 并在上一个完成时订阅下一个。

    我做了一个例子:https://stackblitz.com/edit/angular7-rxjs-jy2gda?file=src/app/app.component.ts

        const APIs = [
          `https://jsonplaceholder.typicode.com/todos/1`,
          `https://jsonplaceholder.typicode.com/todos/2`,
          `https://jsonplaceholder.typicode.com/todos/3`,
          `https://jsonplaceholder.typicode.com/todos/4`
        ].map(url => this.http.get(url));
        from(APIs)
          .pipe(concatAll())
          .subscribe();
    

    【讨论】:

    • from(APIs).pipe(concatAll()) 正在将数组转换为流,然后将流的值存储在数组中。您可以在没有from 的情况下执行此操作。在这种情况下,from(APIs).pipe(concatAll())concat(APIs) 相同。
    【解决方案2】:

    merge:并行运行 observable 数组,在结果到达时一次发出一个结果:

    我们会将结果记录到控制台。

    const obsArray = [randomQuote(), getCatFacts(4), recipeSearch('oil')];
    merge(...obsArray).subscribe(console.log);
    

    forkJoin:并行运行 observables 数组,将结果作为数组发出

    数组实际上是每个 observable 发出的最终值。这意味着它们必须都发出 > 0 的值并且必须全部完成。通常用于 HTTP GET 请求。

    const obsArray = [randomQuote(), getCatFacts(4), recipeSearch('oil')];
    forkJoin(obsArray).subscribe(console.log);
    

    concat: 按顺序运行 observables 数组

    等待obsArray[0]完成后再开始obsArray[1]等等...

    const obsArray = [randomQuote(), getCatFacts(4), recipeSearch('oil')];
    concat(...obsArray).subscribe(console.log);
    

    运算符数组

    这应该很像concat,尽管真正推荐/需要它的情况很少而且相差甚远。请改用concat

    pipe 的实现方式旨在为 typescript 提供一种方法来检查类型在整个功能组合中是否匹配。缺点是它似乎不适用于扩展运算符。我很确定忽略这个 TS 错误是安全的。

    GitHub:.pipe fn type overloads no longer support using spread arguments #3989

    const obsArray = [randomQuote(), getCatFacts(4), recipeSearch('oil')];
    const operatorFunctions = obsArray.map(obs => rxops.switchMap(_ => obs));
    
    const pipeline = of(1).pipe(
      // @ts-ignore
      ...operatorFunctions
    );
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2022-01-14
      • 1970-01-01
      • 1970-01-01
      • 2022-01-20
      • 1970-01-01
      • 1970-01-01
      • 2019-10-02
      相关资源
      最近更新 更多