Home > other >  How to call sequentially Http request and push the results in different lists?
How to call sequentially Http request and push the results in different lists?

Time:01-27

I have multiple http request to call in order and sequentially,

const req = [
  this.domainService.getDomain(filterNG).pipe(map(resp => resp.data), finalize(() => this.loadingNG = false)),
  this.domainService.getDomain(filterCodAML).pipe(map(resp => resp.data), finalize(() => this.loadingCodAML = false)),
  this.domainService.getDomain(filterTipoRating).pipe(map(resp => {
    resp.data.unshift({code: this.TIPO_RATING_ALL, description: this.translate.instant('tutti')});
    return resp.data;
  }), finalize(() => this.loadingTipiRating = false)),
  this.komodoService.listProvince$().pipe(finalize(() => this.loadingProvince = false)),
  this.domainService.getDomain(filterGRA).pipe(map(resp => resp.data), finalize(() => this.loadingGRA = false)),
  this.anagraficaService.getListaFiliali({filter: {all: false}})
    .pipe(map(resp => resp.data), finalize(() => this.loadingFiliali = false))

]

I use concatMap to start calling the http request in order.

from(req).pipe(
  concatMap((request) => request.pipe()),
).subscribe(resp => { console.log(resp)})

My problem and purpose is that I want to push each resp in a different list because each http service return a different response and values and I have to use these in different html list.

I don't know how to save each returned response cause it's returning the single object and not array, it just emit an object each time.

CodePudding user response:

Use forkJoin

forkJoin(req).subscribe(arrayOfResponss=>doSomethingWithIt)

CodePudding user response:

You can make an object with all requests and use different keys that you'll pass to your subscribe() handler to distinguish where it came from:

import { of, map, concatMap, from } from 'rxjs';

const sources = {
  key1: of(123),
  key2: of('abc'),
};

from(Object.entries(sources))
  .pipe(
    concatMap(([key, obs$]) => obs$.pipe(
      map(result => ({ key, result })),
    ))
  )
  .subscribe(console.log);

Working demo: https://stackblitz.com/edit/rxjs-lgagzk?devtoolsheight=60&file=index.ts

  • Related