deathknight256
deathknight256

Reputation: 315

RXJS: How to combine into an array multiple HTTP Requests that returns an object

Hi I have a method that returns an object, I plan to call n number of times and combine into an array after making the last successful call.

  public getActivity({minprice, maxprice, type}: QueryParams) {
    const url = `${BASE_URL}?minprice=${minprice}&maxprice=${maxprice}&type=${type}`;
    return this.httpClient.get(url);
  }

I'm not really sure on how to do it in rxjs but my expected output would be like this:

activities = [{
  fetchedItemId: 1
},
{
  fetchedItemId: 2
},
{
  fetchedItemId: 3
}
]

Upvotes: 0

Views: 60

Answers (1)

deathknight256
deathknight256

Reputation: 315

  getActivity() {
    from(new Array(5))
    .pipe(
      mergeMap(() => this.appService.getActivity(this.filter)),
      filter((activity: Activity) => !activity.error),
      toArray(),
    )
    .subscribe((activities: Activity[]) => {
      this.activities = activities;
    });
  }

I managed to solve it with a combination of pipe, mergeMap, filter and toArray

Upvotes: 1

Related Questions