2016-05-23 186 views
2

類似於this問題,我在Angular2路由器的Release Candidate版本中遇到嵌套路由問題。Angular2新(RC1)路由器,嵌套路由器插座導航

目前,我有一個設置了路線定義應用程序如下

  • 在SRC /客戶

    /應用/ app.component.ts

    @Routes([ 
        // some other routes up here 
        { path: '/', component: HomeComponent } 
        { path: '/admin', component: AdminComponent } 
    ]) 
    
  • 在SRC

    /客戶/應用/+admin/admin.component.ts

    @Routes([ 
        // some other routes up here 
        { path: '/dashboard', component: DashboardComponent }, 
    ]) 
    

我應該注意到AppComponent和AdminComponent都使用<router-outlet>。當您訪問/admin/dashboard時,您嵌套在AdminComponent的路由器插座中,該組件位於AppComponent的路由器插座中

因爲我在管理部分工作,所以我希望在任何路由時進行權限檢查訪問/admin開始。如果用戶沒有適當的權限,他們將被導航到主頁。目前,我試圖做到這一點的方法是

  • 在SRC /客戶/應用/ +管理/ admin.component.ts

    ngOnInit(): void { 
        if (the user does not have the right permissions) { 
        this.router.navigate(['/']); 
        } 
    } 
    

這導航到應用程序的根但是會從AdminComponent模板中引發一個錯誤,因爲它試圖爲AdminComponent中的另一條路由創建一個routerLink。我的直覺是,雖然路徑是正確的,但我仍然位於AdminComponent中的<router-outlet>。不知何故,這可能是由於新路由器想要相對路徑。我不確定如何導航到應用程序的根目錄並將組件加載到正確的路由器插座中。我認爲這是可以在舊的angular2路由器中使用router.parent來解決的問題,但由於這種情況不可用,我需要另一種解決方案。

這裏是日誌在控制檯中的錯誤。

TypeError: Cannot read property 'map' of null 
     at UrlTree.Tree.pathFromRoot (segments.ts:32) 
     at _findUrlSegment (link.ts:87) 
     at _findStartingNode (link.ts:98) 
     at Object.link (link.ts:19) 
     at Router.createUrlTree (router.ts:145) 
     at RouterLink._updateTargetUrlAndHref (router_link.ts:55) 
     at RouterLink.Object.defineProperty.set [as routerLink] (router_link.ts:43) 
     at DebugAppView._View_AdminComponent0.detectChangesInternal (AdminComponent.template.js:247) 
     at DebugAppView.AppView.detectChanges (view.ts:243) 
     at DebugAppView.detectChanges (view.ts:345) 

UPDATE

此前,routerLink S IN的AdminComponent模板是相對路徑,即

<a [routerLink]="['dashboard']" title="Dashboard">Dashboard</a> 

它們更改爲絕對路徑似乎擺脫錯誤的,正確定位到根路線。現在:

<a [routerLink]="['/admin/dashboard']" title="Dashboard">Dashboard</a> 
+0

那麼,你的UPDATE是解決方案嗎? – nadav

+0

是的,路由器鏈接是基於URL的,而不是基於路由的。要了解更多信息,請點擊http://victorsavkin.com/post/145672529346/angular-router,特別是RouterLink - More on Syntax部分@nadav –

回答

0

錯誤消息表明這是您遇到的問題https://github.com/angular/angular/issues/8567

我也沒有看到在您的問題中提供的代碼中配置的路由/,該代碼由this.router.navigate(['/']);使用。

+0

我已經在AppComponent中定義了'/ /'作爲路由,把它包括在我的例子中。我已更新我的問題以反映這一點。我同意你在這個問題上的評論,因爲我沒有用'* ngFor'生成路線。 –

+0

你可以試着把'/'路線移到'/ admin'路線下面嗎? –

+1

使AdminComponent絕對路徑中的'routerLinks'似乎工作。我看到更新超過 –