键入父URL时,默认子路由

时间:2018-01-23 12:24:30

标签: angular

以下是我的路线的样子:

{
    path:'c/:competId',
    component: CompetitionComponent,
    children: [
      {
        path:'overview',
        component: CompetitionDescriptionComponent
      },
      {
        path:'leaderboard',
        component: CompetitionLeaderboardComponent
      },
      {
        path:'submit',
        component: CompetitionSubmitComponent
      }
    ]
  }

每当用户输入c/:competId网址时,我希望他默认重定向到overview路由

所以我尝试将它实现到CompetitionComponent

的init函数中
this.activatedRoute.params.subscribe((params: Params) => {
   this.router.navigate(['c/' + params.competId + '/overview'])
});

但是当我尝试通过网址访问leaderboard时,我会将其重定向到overview。我不想要这种行为。

知道如何解决这个问题吗?

2 个答案:

答案 0 :(得分:1)

你有很多方法可以做到这一点......首先是解决方案,重定向:

{
    path:'c/:competId',
    component: CompetitionComponent,
    children: [
      {
        path:'',
        redirectTo: 'overview',
        pathMatch: 'prefix'
      },
      {
        path:'overview',
        component: CompetitionDescriptionComponent
      },
      {
        path:'leaderboard',
        component: CompetitionLeaderboardComponent
      },
      {
        path:'submit',
        component: CompetitionSubmitComponent
      }
    ]
  }

第二个解决方案,与您的组件的整个路线:

{
    path:'c/:competId',
    component: CompetitionComponent,
    children: [
      {
        path:'',
        component: CompetitionDescriptionComponent
      },
      {
        path:'overview',
        component: CompetitionDescriptionComponent
      },
      {
        path:'leaderboard',
        component: CompetitionLeaderboardComponent
      },
      {
        path:'submit',
        component: CompetitionSubmitComponent
      }
    ]
  }

答案 1 :(得分:0)

将您的路线配置更改为:

{
    path:'c/:competId',
    component: CompetitionComponent,
    children: [
      { path: '', redirectTo: 'overview', pathMatch: 'full' },
      {
        path:'overview',
        component: CompetitionDescriptionComponent
      },
      {
        path:'leaderboard',
        component: CompetitionLeaderboardComponent
      },
      {
        path:'submit',
        component: CompetitionSubmitComponent
      }
    ]
}