我有一个组件X,需要订购多个可观察物的结果,然后才将此结果发送给组件Y。 这些是必须以某种方式组合以产生我需要的结果的可观察对象:
//一旦有了作为对象的城市,我就需要它的属性-cityLocation
a)
如果它是假的,我需要:
b)
a)和b)是我需要发送给组件Y(以及下一个)的结果。如何链接所有这些可观察物?
答案 0 :(得分:1)
使用像switchmap这样的高级地图运算符:
nearbyCities$ = getChosenCityId.pipe(
switchMap(id => getCityById(id)),
switchMap(city => getCitiesByLocation(city.location)),
);
答案 1 :(得分:1)
有点难以解释,但类似...
this.getChosenCityId.pipe( // get id
switchMap(id => this.getCityById(id)), // fetch the city
withLatestFrom(this.getNearbyCities), // with the latest from get nearby
switchMap(([city, getNearby]) =>
getNearby // if get nearby, then get cities by location and map
? this.getCitiesByLocation(city.location).pipe(map(nearbyCities => ({city, nearbyCities})))
: of({city}) // else just return the city
)
).subscribe(result => console.log(result))
如果您还想在getNearbyCities
发生更改时自动更新,则设置会有所不同:
combineLatest(this.getChosenCityId, this.getNearbyCities).pipe( // run when either emits
switchMap(([id, getNearby]) =>
this.getCityById(id).pipe(
switchMap(city =>
getNearby
? this.getCitiesByLocation(city.location).pipe(map(nearbyCities => ({city, nearbyCities})))
: of({city})
)
)
)
).subscribe(result => console.log(result))