2016-10-22 174 views
1

當路由變爲「main」時,我有一個組件被加載。 我在其路由中定義了一個名爲'測試'的子路由帶路由器插座的角度2兒童路由

當路由設置爲main/test時,我希望測試組件在主組件中加載。在主要組件內部,我有一個路由器插座來顯示子組件。

這裏是我的main.routes.ts:

import { Route } from '@angular/router'; 
    import { MainComponent } from './main.component'; 
    import { TestComponent } from './test/test.component'; 
    import { SessionGuard } from '../../services/session/session.guard'; 

    export const MainRoutes: Route[] = [ 
     { 
     path: 'main', 
     component: MainComponent, 
     canActivate: [SessionGuard], 
     children: [ 
     { path: 'test', component: TestComponent } 
    ] 
    } 
]; 

在主要部件html的我:

Main 
<router-outlet></router-outlet> 

我得到的錯誤是: 不能匹配任何路由主/測試

按鈕,觸發路由變化:

<button type="button" class="btn btn-default" (click)="changeRoute('main/test');" >Test</button> 

方法來改變路線:

changeRoute(route: string) { 
    event.stopPropagation(); 
    this.router.navigate([route]); 
} 

感謝

+0

你怎麼重定向到測試?它是一個默認的子路由wihin maincomponent? – micronyks

+0

是的,它是一個兒童組件。主要我有。我使用一個按鈕來重定向,也嘗試只用地址欄。 – Pete

+0

那麼請同時發佈按鈕的工作方式?你的代碼是什麼? – micronyks

回答

2

router-outlet不能爲空。這意味着當您重定向到主要組件時,您沒有任何默認的子路由器集。你只需要設置如下圖所示,

export const MainRoutes: Route[] = [ 
     { 
     path: 'main', 
     component: MainComponent, 
     canActivate: [SessionGuard], 
     children: [ 
        {path:'',redirectTo:'test', pathMatch: 'full'}, 
        {path: 'test', component: TestComponent } 
    ] 

如果你想重定向到test與按鈕的點擊事件只有這樣,你應該使用下面的配置,

export const MainRoutes: Route[] = [ 
     { 
     path: 'main', 
     component: MainComponent, 
     canActivate: [SessionGuard], 
     children: [ 
        {path:'',component:null},  //<<<<### here with null value 
        {path: 'test', component: TestComponent } 
    ]