更新:
现在Angular2 final正式发布,正确的方法如下:
export class ChildComponent { private sub: any; private parentRouteId: number; constructor(private route: ActivatedRoute) { } ngOnInit() { this.sub = this.route.parent.params.subscribe(params => { this.parentRouteId = +params["id"]; }); } ngOnDestroy() { this.sub.unsubscribe(); } }
原版的:
以下是我使用"@ angular/router":"3.0.0-alpha.6"包的方法:
export class ChildComponent { private sub: any; private parentRouteId: number; constructor( private router: Router, private route: ActivatedRoute) { } ngOnInit() { this.sub = this.router.routerState.parent(this.route).params.subscribe(params => { this.parentRouteId = +params["id"]; }); } ngOnDestroy() { this.sub.unsubscribe(); } }
在此示例中,路由具有以下格式:/ parent /:id/child /:childid
export const routes: RouterConfig = [ { path: '/parent/:id', component: ParentComponent, children: [ { path: '/child/:childid', component: ChildComponent }] } ];
你不应该尝试使用RouteParams
你的ChildOneComponent
.
请RouteRegistry
改用!
@Component({ ... }) export class ChildOneComponent { public username: string; constructor(registry: RouteRegistry, location: Location) { route_registry.recognize(location.path(), []).then((instruction) => { console.log(instruction.component.params['username']); }) } ... }
更新:从此拉取请求(角度β9):https://github.com/angular/angular/pull/7163
您现在可以在不使用的情况下访问当前指令recognize(location.path(), [])
.
例:
@Component({ ... }) export class ChildOneComponent { public username: string; constructor(_router: Router) { let instruction = _router.currentInstruction(); this.username = instruction.component.params['username']; } ... }
我还没有尝试过
更多详情:
https://github.com/angular/angular/blob/master/CHANGELOG.md#200-beta9-2016-03-09 https://angular.io/docs/ts/latest/api/router/Router-class html的
更新2: 从角度2.0.0.beta15开始的小变化:
现在currentInstruction
不再是一个功能了.此外,您必须加载root
路由器.(感谢@ Lxrd-AJ报道)
@Component({ ... }) export class ChildOneComponent { public username: string; constructor(_router: Router) { let instruction = _router.root.currentInstruction; this.username = instruction.component.params['username']; } ... }
如GünterZöchbauer所述,我使用https://github.com/angular/angular/issues/6204#issuecomment-173273143上的评论来解决我的问题.我使用Injector
类angular2/core
来获取父级的routeparams.原来角度2不能处理深层嵌套的路线.也许他们将来会添加它.
constructor(private _issueService: IssueService, private _injector: Injector) {} getIssues() { let id = this._injector.parent.parent.get(RouteParams).get('id'); this._issueService.getIssues(id).then(issues => this.issues = issues); }
我找到了一个丑陋但有效的解决方案,通过请求父母(正是第二个祖先)注射器,并RouteParams
从此处获取.
就像是
@Component({ ... }) export class ChildOneComponent { public username: string; constructor(injector: Injector) { let params = injector.parent.parent.get(RouteParams); this.username = params.get('username'); } }