【问题标题】:Do we need RXJS combineLatest with ActivateRouted.pathFromRoot?我们需要 RXJS combineLatest 和 ActivateRouted.pathFromRoot 吗?
【发布时间】:2021-01-23 00:17:32
【问题描述】:

Angular Material Documentation 应用程序从延迟加载的路由模块中检索路由参数,如下所示:

https://github.com/angular/material.angular.io/blob/master/src/app/pages/component-category-list/component-category-list.ts

// Combine params from all of the path into a single object.
    this.params = combineLatest(
        this._route.pathFromRoot.map(route => route.params), Object.assign);

看来我们真的不需要 combineLatest 来做这个?

_route 是构造函数注入的,IIUC 一旦组件引用它,ActivateRoute 实例的pathFromRoot 数组就不能更改?

既然这样我们就不需要combineLatest

看来我们可以这样做:

const paramArr = this._route.pathFromRoot.map(route => route.params)

this.params = of(Object.assign(paramArr))

这有意义吗?

【问题讨论】:

    标签: javascript angular typescript rxjs


    【解决方案1】:

    const paramArr = this._route.pathFromRoot.map(route => route.params)
    

    pathFromRoute 因此route 不会改变。但是route.params 是一个 Observable,这个 Observable 可以随着时间的推移发出新的值。要在其中一个 Observable 发出新值时收到通知,您必须订阅所有这些 Observable。这就是使用combineLatest 的原因。


    this.params = of(Object.assign(paramArr))
    

    真的没用。它创建了一个 Observable,它发出一个 Observable 数组,所以你必须在另一个步骤中展平这个 Observable。当您使用combineLatest 时,您将不需要这个额外的步骤。

    【讨论】:

      【解决方案2】:

      看来我们真的不需要 combineLatest?

      我会说它是必要的,但这也取决于您想要实现的目标。

      例如,使用这种方法:

      const paramArr = this._route.pathFromRoot.map(route => route.params)
      
      this.params = of(Object.assign(paramArr))
      

      您将获得从 ActivatedRoute 根到当前 ActivatedRoute 子级的参数只有一次。这意味着如果路由的params 得到更新(例如,首先导航到/1,然后导航到/2),你只会得到1。 另外,我不确定这是否会按预期工作,因为paramsArr 将是一个可观察的数组(ActivatedRoute.paramsBehaviorSubject AFAIK)。

      如果你使用这种方法:

      this.params = combineLatest(
              this._route.pathFromRoot.map(route => route.params), Object.assign);
      

      您将收到关于ActivatedRoute 树中发生的所有params 更新的通知,不仅是一次,而是每次。

      我在this article 中详细说明了ActivatedRoute 的工作原理(除其他外)。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2019-07-28
        • 2017-06-25
        • 1970-01-01
        • 1970-01-01
        • 2017-07-30
        • 2021-02-21
        相关资源
        最近更新 更多