Angular2路由在空路由上失败

时间:2017-01-25 05:38:02

标签: angular typescript

我已经设置了这样的路由

我在app模块中有第一级路由

const routes: Routes = [
{ path: 'login', component: LoginComponent, },

 { path: 'dash', redirectTo:"dashboard" },
 { path: '**', component: NotFoundComponent }

];
@NgModule({
  imports: [RouterModule.forRoot(routes)],
  exports: [RouterModule],
  providers: []
 })

在应用组件<router-outlet></router-outlet>

然后我有一个仪表板模块,我已将另一个路由配置设置为

const dashboardRoutes: Routes = [
 {
   path: '',  //null path to use dashboardtemplate which contains sidebar links
   component: DashboardTemplateComponent,
   children: [
  {
    path: 'profile',
    component: ProfileComponent,

  },
  {
    path: 'dashboard',
    component: DashboardComponent, //dashboard is another component

  },
  {
    path: 'users',
    component: UsersComponent,
  },


   ]
 }

 ];

@NgModule({
 imports: [
   RouterModule.forChild(dashboardRoutes)
 ],
 exports: [
    RouterModule
  ]
})

我还有仪表板模板组件

@Component({
  template: `
      <dash-side></dash-side> //sidebar links in the dashboard
      <router-outlet></router-outlet>`
})
export class DashboardTemplateComponent implements OnInit {

//here the logic is if a user is loggedin navigate to dashboard else to login

  }

我之所以这样设置是因为配置文件和用户组件可以使用DashboardTemplate component

中设置的侧边栏链接

问题是,当在仪表板路线中使用配置文件时,它总是会回退到未找到的组件,我该如何解决此问题

1 个答案:

答案 0 :(得分:1)

有很多问题。

  • 重定向路由需要斜杠前缀和pathMatch

  • 将RouterModule导入为主RouterModule.forChild(routes) 路线档案。

  • RouterModule.forRoot()中将imports的路由器模块导入AppModule

这可以解决您的问题。

const routes: Routes = [
    {
        path: 'login',
        component: LoginComponent
    },
    {
        path: 'dash',
        redirectTo:"/dashboard",  // <=== prefix slash
        pathMatch: 'full'         // <=== Add 'pathMatch'
    },
    {
        path: '**',
        component: NotFoundComponent
    }
];
@NgModule({
    imports: [RouterModule.forChild(routes)],  // <=== change to forChild()
    exports: [RouterModule],
    providers: []
})