2016-07-29 71 views
1

从Angular 2组件访问RouterConfig的首选方式是什么?我想检查我目前路线的所有儿童路线。如何从组件访问RouterConfig(Angular2 RC4)

我能够想到的最好的方法是访问ActivatedRouteSnapshot的私有成员变量(_routeConfig)。但宁可不要使用它,因为它可能会发生变化。

见下面的代码片段:

export class MyComponent{ 

    constructor(private _router: Router, 
      private _route: ActivatedRoute) 
    { 

    } 

    private findChildRoute(componentPath : string){ 
    let matchingRoute = (<any>this._route.snapshot)._routeConfig.children.find((T) => T.path == componentPath); 
    return matchingRoute; 
    } 
} 

回答

0

您可以通过访问完整的路由器树。现在

this.router.routerState // tree of activated routers 

你可以用孩子去寻找所有子路由状态ActivatedRoute

constructor(private router:Router, private currentActivatedRoute:ActivatedRoute) 
// this should be called in ngOnInit 
    var state = this.router.routerState 
    var children = state.children(this.currentActivatedRoute) 

RouterStateTree

+0

这是有用的,但并不能完全回答这个问题。您的建议不会返回父组件的所有定义的子路线。相反,它返回一个只有活动子路由的数组。 – noxborough