:id路由覆盖其他

时间:2019-07-16 12:21:50

标签: angular typescript angular-routing

我有以下路线:

const routes: Routes = [

  { path: '', component: UserComponent, children: [
      { path: '', component: LoginComponent },
      { path: 'signup', component: SignupComponent }
    ]},
  { path: 'dashboard', component: MainComponent, children: [
      { path: '', component: DashboardComponent, children: [
          { path: '', redirectTo: '0', pathMatch: 'full' },
          { path: '0', component: NoListComponent },
          { path: ':id', component: ListComponent },
        ]},
      { path: 'createlist', component: CreateListComponent },
      { path: 'create', component: CreateTaskComponent }
    ]},
];

以某种方式,当我调用routerLink="dashboard/create"routerLink="dashboard/createlist"时,显示的ListComponent(:id)没有任何内容,但没有CreateListComponent或CreateTaskComponent。

3 个答案:

答案 0 :(得分:1)

您需要更改路由配置,如下所示:

{
    path: 'dashboard',
    component: MainComponent,
    children: [{
        path: '',
        component: DashboardComponent,
        children: [{
                path: '',
                redirectTo: '0',
                pathMatch: 'full'
            },
            {
                path: '0',
                component: NoListComponent
            },
            {
                path: 'createlist',
                component: CreateListComponent
            },
            {
                path: 'create',
                component: CreateTaskComponent
            },
            {
                path: ':id',
                component: ListComponent
            }
        ]
    }]
}

这是必需的,因为/createlist/create都是/dashboard的子代。还要注意上面列出的路径的顺序。

答案 1 :(得分:1)

您的路线在角度上有些混乱。当您致电/dashboard/create时,angular认为您正在尝试将ID值设置为“ create”来访问/dashboard/:id。您的路径应该是唯一的,并且不会产生歧义。

我会这样声明

{ path: '', component: DashboardComponent, children: [
          { path: '', redirectTo: 'no-list', pathMatch: 'full' },
          { path: 'no-list', component: NoListComponent },
          { path: 'list/show/:id', component: ListComponent },
          { path: 'list/createlist', component: CreateListComponent },
          { path: 'list/createtask', component: CreateTaskComponent },
]}

答案 2 :(得分:1)

以上答案是正确的,我只想澄清一件事。当涉及路由时,顺序很重要。因此,您需要将/createlist/create放在:id

之前
{
  path: 'dashboard', component: MainComponent, children: [
    {
      path: '', component: DashboardComponent, children: [
        { path: '', redirectTo: '0', pathMatch: 'full' },
        { path: 'createlist', component: CreateListComponent },
        { path: 'create', component: CreateTaskComponent },
        { path: '0', component: NoListComponent },
        { path: ':id', component: ListComponent }
      ]
    },

  ]
},

如果将它们放在:id之后,它将覆盖它们,因为:id将匹配/dashboard之后的任何嵌套路由

相关问题