2016-08-03 81 views
0

使用以前的angular2路由器, 我能夠通過url獲取組件名稱。在angular2最新的路由器中通過url獲取組件

  console.log(this.router.instruction); 
      console.log(this.router.currentInstruction.component); 
      console.log(this.router.currentInstruction.component.routeName); 

但與新的路由器我不能。 有沒有其他的選擇?

我想跟蹤我的應用程序所有的路由,然後將它記錄它的組件名稱(不url值)

constructor(private router: Router, 
      private cookieService: CookieService, 
      private adminService: AdminService, 
      private appService: AppService) { 
    router.events.subscribe((e: Event) => { 
     if (e instanceof NavigationEnd) { 

      // 
      // WANT TO GET COMPONENT NAME by this.router.url 
      // 

      let newRoute = this.router.url || '/'; 
      if (this.currentRoute != newRoute) { 
       console.log('route to ', newRoute); 
       this.currentRoute = newRoute; 
      } 
     } 
    }); 
} 

任何機會呢?

回答

0

如果您需要訪問父及部件see

ActivatedRoute

+0

嘿@Arpit阿加瓦爾孩子激活路線,您可以訪問活動路線如下代碼片斷

constructor(private router:Router, private currentActivatedRoute:ActivatedRoute) ngOnInit() { var comp = this.currentActivatedRoute.component } 

。它總是返回相同的組件。我將事件觀察者訂閱到單個組件中以跟蹤站點上的所有路由。 –

+0

查看關聯的帖子。您可以獲取兒童的ActivatedRoute並使用該樹來查找葉節點。您訂閱的組件必須是可以工作的根。 –

+0

或者,你可以寫一個canActivateGuard,它具有與我的文章中描述的相同/相似的參數,並從那裏登錄。您必須在所有元素的路由配置中傳遞該鉤子。順便說一句,沒有登錄ngOnInit的個人組件只要你的用例。 –

相關問題