2016-12-24 105 views
2

如何在使用angular2中的參數的子路由的情況下使用redirectTo。我的路由結構,這樣對於子路由,在angular2中的redirectTo

const appRoutes: Routes = [ 
    { path: '', redirectTo : '/home', pathMatch: 'full'}, 
    { path: 'home', component: HomeComponent}, 
    { path: 'xyz/:id', component: XYZ }, 
    { 
     path: 'abc/:id', component: ABC, 
     children: [ 
      { path: '', redirectTo : 'def', pathMatch: 'prefix' }, 
      { path: 'def/:id', component: DEF } 
     ] 
    } 
] 

但它不工作

還,什麼是路由pathMatch

回答

2

尋找你的示例代碼,如果路徑'abs /:id'和'def /:id'使用相同的參數(:id),我使用的解決方案是忘記子路由配置中的參數其組件從其父路由獲得:

const appRoutes: Routes = [ 
{ 
    path: ':id', 
    component: SimulatorComponent, 
    children: [ 
     { 
      path: 'home', 
      component: HomeComponent 
     } 
    ] 
} 

];

在HomeComponent,那麼你趕上從父路線ID:

export class HomeComponent implements OnInit { 
    protected id: number; 

    constructor(protected route: ActivatedRoute) { 
    } 

    ngOnInit() { 
     this.route.parent.params.subscribe(params => this.id = +params['id']); 
    } 

}

+0

對不起,但在我的情況下'ID'是不一樣的;)現在該做什麼? –

1

您應該重定向到home(不帶斜槓),因爲您的redirectTo值需要匹配給定的path,而不是任意的url。

有關pathMatch屬性的詳細信息,請參閱Angular2的Routing & Navigation文檔中的部分。

+1

如果你在'redirectTo'中的一個url之前加了一個斜槓,這意味着它是一個絕對的重定向url。所以它是有效的。如果這改變了,請糾正我。 – echonax

1

pathMatch = '全' 導致路線命中時,URL匹配的剩餘未匹配的段是前綴路徑

pathMatch ='前綴'告訴路由器匹配重定向路由時,其餘的URL 開始與重定向路由的前綴路徑。

編號:https://angular.io/docs/ts/latest/guide/router.html#!#redirect

那麼讓我們來看看你的例子:

const appRoutes: Routes = [ 
    { path: '', redirectTo : '/home', pathMatch: 'full'}, 
    { path: 'home', component: HomeComponent}, 
    { path: 'xyz/:id', component: XYZ }, 
    { 
     path: 'abc/:id', component: ABC, 
     children: [ 
      { path: '', redirectTo : 'def', pathMatch: 'prefix' }, //error 
      { path: 'def/:id', component: DEF } 
     ] 
    } 
] 

錯誤行表示如果輸入類似abc/1 + ''(這是abc/1),redirectTo = 'def'(完整路徑= 'abc/:id/def')不存在。

隨着pathMatch = prefix如果你輸入後,因爲這abc/1 + ''匹配''任何URL,因爲1後每個URL都會有一個空字符串abc/1後任何它仍然會嘗試redirectTo = 'def'(例如abc/1/longesturl)。

+0

準確地解釋了答案所以最新的解決方案是什麼 –

+0

@PardeepJain如果你想它被重定向到「def''路徑,那麼你必須創建一個」def「路徑 – echonax

+0

但我沒有名爲Def的路徑而不是用參數def。現在該怎麼辦?任何想法 –