Angular 8和可链接观察

时间:2019-12-13 16:44:52

标签: angular rxjs observable

我有一个组件X,需要订购多个可观察物的结果,然后才将此结果发送给组件Y。 这些是必须以某种方式组合以产生我需要的结果的可观察对象:

  1. getChosenCityId(behaviourSubject)// //一旦获得ID,就可以像这样获得城市信息:
  2. getCityById(id)(http调用的结果)

//一旦有了作为对象的城市,我就需要它的属性-cityLocation

  1. getCitiesByLocation(cityLocation)(http调用的结果)//前一行的cityLocation
  2. getNearbyCities。 (behaviorSubject)返回一个布尔值。如果是真的,我需要

a)

  • citiesByLocation(4。)
  • chosenCityId(1。)

如果它是假的,我需要:

b)

  • 城市(2。)
  • chosenCityId(1。)

a)和b)是我需要发送给组件Y(以及下一个)的结果。如何链接所有这些可观察物?

2 个答案:

答案 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))
相关问题