【问题标题】:Angular 8 and chaining observablesAngular 8 和链式 observables
【发布时间】:2019-12-13 16:44:52
【问题描述】:

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

  1. getChosenCityId (behaviourSubject) // 一旦我有了 id,我就可以像这样得到城市:
  2. getCityById(id)(http 调用的结果)

// 一旦我有了城市,这是一个对象,我需要它的属性——cityLocation

  1. getCitiesByLocation(cityLocation)(http 调用的结果)//来自上一行的 cityLocation
  2. 获取NearbyCities。 (behaviorSubject) 返回一个布尔值。如果是真的,我需要

一)

  • citiesByLocation (4.)
  • chosenCityId (1.)

如果是假的,我需要:

b)

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

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

【问题讨论】:

  • this..实际上,有很多关于链接可观察对象的问题,肯定有些问题会对你有所帮助。

标签: angular rxjs observable


【解决方案1】:

使用更高级别的地图运算符,例如 switchmap:

nearbyCities$ = getChosenCityId.pipe(
  switchMap(id => getCityById(id)),
  switchMap(city => getCitiesByLocation(city.location)),
);

【讨论】:

    【解决方案2】:

    有点难以解释,但有点像......

    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))
    

    【讨论】:

    • 非常感谢,这似乎非常符合我的要求!!我会试试的,让你知道!我只是不明白这一行(对不起,对此很陌生..):this.getCitiesByLocation(city.location).pipe(map(nearbyCities => ({city, nearCities}))) ---- getCitiesByLocation 是也是一个可观察的,我可以用这种方式订阅它吗?非常感谢您的宝贵时间和非常有用的回复!
    • switchMap 正在处理订阅,它只是附加了一个内部地图来保存城市数据
    • 好的,知道了!再次感谢你!是的,如果 selectedId 发生变化或 getNearbyCities 发生变化,我需要自动更新它(应该早点提到它......)。
    • 但我认为两者都在同时变化,所以应该没问题..
    • 我将其改为使用 combine
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-01-02
    • 2018-03-21
    • 2018-05-05
    • 2016-09-07
    • 2018-05-11
    相关资源
    最近更新 更多