【问题标题】:How to accumulate the data from multiple requests如何从多个请求中累积数据
【发布时间】:2019-06-06 09:24:27
【问题描述】:

我有一个创建多个请求的服务函数:

getData(): Array<Observable<AxiosResponse<Data>>> {
    const data = [];
    for (let i = 1; i <= end; i++) {
      data.push(
        this.http.get<Data>(
          getUrl(i),
        ),
      );
    }
    return data;
  }

我有一个控制器功能:

@Get()
get() {
    return this.appService.getData().forEach(x => {
      x.subscribe(y => {
        // need to accumulate the data from each request and return that as a single json
      });
    });
  }

您将如何在控制器方法中累积来自每个请求的所有数据 并将其作为单个 json 返回?有什么想法吗?

如果我这样做:

  @Get()
  get() {
    const data = [];
    return this.appService.getData().forEach(x => {
      x.subscribe(y => {
        data.push(...y.data);
      });
      return data;
    });
  }

不会工作,因为 return data 将在实际的 .subscribe(...) 之前执行

y.data 是一个对象数组,例如:

[
 {key:"xyz", value:123 },
 {key:"abc", value:666 }
]

【问题讨论】:

    标签: typescript rxjs nestjs


    【解决方案1】:

    您可以使用 rxjs 运算符更好地处理它。

    import { Observable, range } from 'rxjs';
    import { concatMap, toArray } from 'rxjs/operators';
    
    const source: Observable<Data[]> = range(1, end)
      .pipe(
        concatMap((i: number) => this.http.get<Data>(getUrl(i))),
        toArray()
      );
    

    那你就可以订阅这个来源了:

    source.subscribe((data: Data[]) => {
      // Do some stuff with data
    });
    

    【讨论】:

    • 看来我确实需要用 range 东西等替换 for 循环
    • range 是从哪里来的?
    • 让我添加导入。
    • import { range } from 'rxjs';
    猜你喜欢
    • 2016-06-18
    • 1970-01-01
    • 1970-01-01
    • 2016-03-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多