这是羽毛球:http://embed.plnkr.co/B8feYX7e6oxvI2u4zmYW/
点击“儿童1” - 有效。现在点击“Child 2” - 不起作用。 单击“主页”。 点击“Child 2” - 工作。现在点击“Child 1” - 不起作用。
基本上,从应用程序根目录导航到嵌套路由器出口只能在每个应用程序生命周期中运行一次,或者直到您必须先导航回根目录。
以下是一些代码(请查看完整版的plunker):
app.component
@Component({
selector: 'my-app',
directives: [ROUTER_DIRECTIVES],
template: `
<div>
<a [routerLink]="['/']">HOME</a>
<a [routerLink]="['/child', 1]">Child 1</a>
<a [routerLink]="['/child', 2]">Child 2</a>
</div>
<div>
<router-outlet></router-outlet>
</div>
`
})
@Routes([
{ path: 'child/:id', component: ChildContainerComponent }
])
export class AppComponent { }
儿童-container.component
@Component({
directives: [ROUTER_DIRECTIVES],
template: `
<div>
<h3>Child outer container</h3>
<router-outlet></router-outlet>
</div>
`
})
@Routes([
{ path: '/', component: ChildComponent }
])
export class ChildContainerComponent{
}
child.component
@Component({
template: `
<div>
Child: Id={{_id}}
</div>
`
})
export class ChildComponent implements OnInit {
private _id: number;
private get routeSegment(): RouteSegment { // must be better way to get value
return this._router.routeTree._root.children[0].value;
}
constructor(private _router: Router) {
}
ngOnInit() {
this._id = +this.routeSegment.getParam('id');
}
}
答案 0 :(得分:2)
您需要将AppComponent路由更改为:
@Routes([
{ path: '/child', component: ChildContainerComponent }
])
您的ChildContainerComponent路由到:
@Routes([
{ path: ':id', component: ChildComponent }
])
获得这些路线后,您可以通过实施OnActivate
接口获取ID:
import { Router, RouteSegment, RouteTree, OnActivate, Routes } from '@angular/router';
export class ChildComponent implements OnInit, OnActivate {
private _id: number;
routerOnActivate(currRoute: RouteSegment,
prevRoute?: RouteSegment,
currTree?: RouteTree,
prevTree?: RouteTree) {
this._id = +currRoute.getParam('id');
}
}
这是一个有效的plunker