2016-07-29 78 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