Artsiom Krukouski
Artsiom Krukouski

Reputation: 57

how to change the data of the first observable using data from another observable including the condition in angular/rxjs

I ran into a problematic one, let me provide the example schematically without any business details, so I'm fetching some data (e.g. cars via getCars()) from an API that returns an Observable. And I need to get the data from another endpoint by car model (e.g. features via getFeatures(model)) and then replace features data(we should do it for each car).

Addition to the question, how can we embed a conditional operator to make a request for getFeatures(...) only when (model === 'porsche')?

this.getCars().pipe(
 map(cars => {
 ...
}))
.subscribe(cars => {})

export interface Car {
   id: string,
   model: string,
   engine: string,
   details: Detail[]
}

export interface Detail {
   features: string[]
   ...
}

Could you tell me if you have any ideas? that will be very helpful.. thanks in advance :)

Upvotes: 0

Views: 100

Answers (1)

wlf
wlf

Reputation: 3413

let cars$ = getCars();
let carsWithFeatures$ = cars$.pipe(
  map((cars) =>
    cars
      .filter((car) => car.model === 'porsche')
      .map((car) =>
        getFeatures(car.model).pipe(map((features) => ({ ...car, features })))
      )
  ),
  mergeMap((cars$) => forkJoin(cars$))
);
  • use plain JS array filter to filter out all expect Porsche
  • use plain JS array map to call the feature service for each remaining car in the list
  • combine the features result with the matching car (I have simplified your model a bit)
  • use mergeMap and forkJoin to combine the items back into a single (array) object for emission by carsWithFeatures$

Stackblitz(check console tab): https://stackblitz.com/edit/rxjs-drukvp

Upvotes: 2

Related Questions