【问题标题】:Angular 4 subscribe of paramMap not working with children outletAngular 4 订阅 paramMap 不能与儿童插座一起使用
【发布时间】:2017-08-23 14:54:12
【问题描述】:

在我们的Angular 4 App 中,我们有一个带有合同列表的下拉菜单。

一旦用户选择了一个合约,我们就会触发一个router.navigate,用选定的contractId 更改网址,然后我们用它创建一个http request

其实很简单:

this.activatedRoute.paramMap.subscribe(...request with contractId...)

这适用于平坦路线。

但是在有孩子的路线上它不起作用,例如这条路线:

export const customerRoutes: Routes = [
{
    path: ":contractId/Customers",
    component: CustomersComponent,
    children: [
        { path: "", redirectTo: "Children", pathMatch: "full" },
        { path: "Children", component: ChildrenComponent }
    ]
  }
];

上面的路线给了我以下网址: http://localhost:4033/20917/Customers/Children

现在假设我想在 DropDown 中选择一个新合同...

...那是 DropDown 的onChange

public onChange(contract: Contract): void {
  this.router.navigate([contract.id, window.location.pathname.split("/")[3]]);
}

window.location.pathname.split("/")[3] 给我的信息:客户

网址更改为http://localhost:4033/33444/Customers/Children,但未点击订阅。为什么?

【问题讨论】:

  • 此代码在哪里:this.activatedRoute.paramMap.subscribe(...request with contractId...)?它只会获取与组件关联的路由的更改。因此,要获取Children 路由更改,此代码需要位于Children 组件中。是这样吗?
  • 感谢@DeborahK - 是的,这正是它所在的位置 - 订阅者在子组件中。用 plunker 应该很容易重现这个。我试试看……
  • 我可以解决@DeborahK 的问题,这很有趣。我在网上没有看到太多关于此的内容。我还尝试了复数课程,但那里没有涉及。当您在子组件中并想通过订阅访问父组件的参数时,需要使用:this.activatedRoute.parent.paramMap... 然后它可以工作。我将通过指向 plunker 的链接发布答案
  • 很高兴你知道了。我确实在 Pluralsight 上的 Angular Routing 课程中讨论了激活路由的 .parent 属性,但与观看数据属性有关。它在概念上很相似。

标签: angular routes


【解决方案1】:

要监视父组件的更改事件,我们需要显式调用:

this.activatedRoute.parent.paramMap.subscribe(...request with contractId...)

这不在文档中,我已经为此创建了一个请求:https://github.com/angular/angular/issues/18862

【讨论】:

  • 看起来你关闭了这个问题。我问为什么?我现在有类似的问题,但还没有找到解决方案..
  • 这是对文档和功能的请求,而不是问题。上面给出了解决方案
  • @DAG 你能用 pipe() 操作符展示如何做到这一点吗?从 Angular 6 开始,你不能再使用 .map 了。我试着像这样重新创建你在 plunkr 中所做的:`this.activatedRoute.parent.paramMap.pipe(map(m => m.get("contractId")), distinctUntilChanged ((previous: any, current: any) => {return true})).subscribe(),` 但它不起作用。
【解决方案2】:

对我来说,activatedRoute.parent.parentMapactivatedRoute.parentMap 都不起作用。经过一些试验和错误,我想出了以下解决方案:

const params$ = router.events
    .pipe(map(() => _.assign({}, activatedRoute.snapshot.params, activatedRoute.firstChild?.snapshot.params)));

这终于显示了所有参数。它显然应该去抖动,因为路由器会发出很多事件,但这是我能找到的最好的。

我正在使用 Angular 11。

【讨论】:

    猜你喜欢
    • 2019-03-27
    • 1970-01-01
    • 1970-01-01
    • 2017-03-16
    • 2020-04-14
    • 2018-04-01
    • 2020-12-13
    • 2018-11-23
    • 2018-11-26
    相关资源
    最近更新 更多