Reputation: 57
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
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$))
);
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