【问题标题】:Angular2 Route with childs in RC6Angular2 路线与 RC6 中的孩子
【发布时间】:2016-09-06 11:42:27
【问题描述】:

我是 Angular2 的新手,我正在尝试将一些路由添加到我的应用程序中。我有两个单独的路由文件:

app.routing.ts

const appRoutes: Routes = [
  {
    path: 'login',
    component: LoginComponent
  },
  {
    path: '',
    component: LoginComponent
  },
  {
    path: '**', component: My404Component
  }
];


export const routing = RouterModule.forRoot(appRoutes);

和dashboard.routing.ts

const appRoutes: Routes = [
  {
    path: 'dashboard',
    component: DashboardComponent,
    children: [
      {
        path: 'child',
        component: ChildComponent,
      },

    ],
    canActivate: [AuthGuard],
  }
];


export const dashboardRouting: ModuleWithProviders = RouterModule.forChild(appRoutes);

如果我访问 http://localhost:3000/dashboard 我会收到 404 页面错误,但如果我访问 http://localhost:3000/dashboard/child 我可以看到该页面。

如果我删除仪表板内的children 属性,我可以访问http://localhost:3000/dashboard 并查看页面...

我做错了什么?

【问题讨论】:

    标签: angular angular2-routing


    【解决方案1】:
    const appRoutes: Routes = [
      { path: '', pathMatch: 'full',  component: LoginComponent }, // order matters
      { path: 'login', component: LoginComponent },
      { path: '**', component: My404Component }
    ];
    

    也为子路由添加默认路由:

    const appRoutes: Routes = [
      { path: 'dashboard', component: DashboardComponent, canActivate: [AuthGuard], children: [
          { path: '', redirectTo: 'child', pathMatch: 'full' },
          { path: 'child', component: ChildComponent, },
      ],
      }
    ];
    

    【讨论】:

    • 您好,感谢您的快速回答:)。现在,随着您的更改,404 页面不会出现,但当我尝试访问 /dashboard 时会自动将我重定向到 /dashboard/child。有没有办法访问 /dashboard 并查看“仪表板的模板”?
    • 如果DashboardComponent 有一个<router-outlet>,则需要提供a 子路由。您可以向path: '' 子路由添加一个不显示任何内容的Dummy 组件,而不是redirectTo
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-01-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多