【发布时间】: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 属性,但与观看数据属性有关。它在概念上很相似。