2016-07-30 33 views
3

我正在嘗試檢查父組件中的活動子路由,但我遇到了問題。Angular2(rc4) - 檢查父組件中的活動子路由

我曾嘗試做這樣的事情訂閱ActivatedRoute:

class ParentComponent { 
    constructor(private _route:ActivatedRoute) {} 

    ngOnInit() { 
     this._route.data.subscribe(value => console.log(value)}); 
    } 
} 

我已經閱讀了很多關於堆棧溢出的線程,但找不到檢查以及關於被更新的解決方案父組件的子路由。

任何想法?

回答

2

您可以使用下面的代碼片段

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

非常感謝:) –

+0

'屬性'兒童'不存在'RouterState''類型...:/ – Inigo

+3

不確定是否因爲此答案發布而發生了變化,但兒童是ActivatedRoute的屬性,而不是路由器 – Inigo

2

在寫這幾行訪問活動子路線,所選答案似乎不工作了。

如果您希望在路線更改時收到通知,您可以訂閱Router.events observable。例如,NavigationEnd事件的URL存儲爲一個屬性:

this.router.events.filter(evt => evt instanceof NavigationEnd) 
        .map(evt =>evt.url) 
        .subscribe(url=>console.log(url)); 

如果要比較當前路線孩子路徑 - 讓我們說"child" - 。您可以使用Router.isActive()方法:

let events = this.router.events; 
events.filter(evt => evt instanceof NavigationEnd) 
     .map(() =>{ 
      let exact=true; 
      let childRoute=this.router.createUrlTree(["child"], {relativeTo: this.route} 
      return this.router.isActive(childRoute,exact); 
     }) 
     .subscribe(active=>console.log(`child route is active :${active`)); 

注:

  • this.router是一個Router實例
  • this.routeActivatedRoute
  • exact一個實例是用來做精確匹配:如果路由是"child/grand-child"this.router.isActive(route,true)會返回假
+0

獲取此錯誤..類型'Event'上不存在'property'url' 'RouteConfigLoadStart'類型中不存在屬性'url' –

+0

@Aakriti您需要過濾路由器事件並僅採用'NavigationEnd'事件。 'this.router.events.filter(evt => evt instanceof NavigationEnd)'(可能需要將類型斷言爲'Observable ',如下所示:'this.router.events.filter(evt => evt instanceof NavigationEnd)作爲Observable ' – n00dl3

+0

我們將如何使用map ..它說'找不到名稱映射表' –

相關問題