Sergino
Sergino

Reputation: 10838

How to accumulate the data from multiple requests

I have a service function that creating a number of requests:

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

I have a controller function:

@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
      });
    });
  }

How would you accumulate all the data from each request in controller method and return that as a single json? Any thoughts?

If i do this:

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

won't work as return data will be executed before the actual .subscribe(...)

y.data is an array of objects like:

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

Upvotes: 0

Views: 244

Answers (1)

s.alem
s.alem

Reputation: 13079

You can handle it better with rxjs operators.

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()
  );

Then you can subscribe to this source:

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

Upvotes: 2

Related Questions