Search code examples
angularrxjsangular-httpclient

Merging httpClient Observables in one dynamically depending on page count


I have API which gives data partialy (by pages). I get page count on first request.

On client I need to concat pages in one Observable. Trying something like this:

all$: Observable<Service[]>;
iterator$ = new BehaviorSubject(1);

constructor(public http: HttpClient) {
  this.all$ = this.iterator$.pipe(
    concatMap(page => http.get<Service[]>('/service', {params: {page: page.toString()}}).pipe(
      tap(() => (ifNotLastPage) ? this.iterator$.next(++page) : null),
    )),
  );
}

and get only last page


Solution

  • Finnaly I got:

    all$: Observable<Service[]>;
    
    constructor(public http: HttpClient) {
      this.all$ = this.getData().pipe(
        expand(result => {
          const next = getNextPageNumber(result);
    
          return (next) ? this.getData(next) : empty();
        }),
        map(result => result.body),
        concatMap(typeCasting(Service)),
        toArray<Service>(),
      );
    
    }
    
    getData(page = 1): Observable<HttpResponse<Config>> {
      return this.http.get<Config>('/service', { observe: 'response', params: { page: page.toString() } });
    }
    

    Thanx to @martin and this article RxJS: Understanding Expand