路由&模块

时间:2017-06-21 18:37:29

标签: angular angular2-routing angular-routing angular-module angular2-modules

我的应用程序中有以下路由配置:

app.module.ts

@NgModule({
  declarations: [
    AppComponent
  ],
  imports: [
    BrowserModule,
    HttpModule,
    AppRouting,

    // Feature Modules
    CoreModule,
    AuthModule,
    AdminModule,
    SharedModule
  ],
  bootstrap: [AppComponent]
})

app.routing.ts

const routes: Routes = [
  { path: '', redirectTo: 'admin', pathMatch: 'full' },
  { path: 'admin', loadChildren: () => AdminModule }
];

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

admin.module.ts

@NgModule({
  declarations: [
    AdminComponent
  ],

  imports: [
    CommonModule,
    FormsModule,
    UserModule,

    AdminRouting,
    SharedModule
  ],

  providers: [
    UserService
  ]
})

admin.routing.ts

const routes: Routes = [
  { path: '', component: AdminComponent, canActivate: [AuthGuard], children: [
    { path: 'users', loadChildren: () => UserModule }
  ]}
];

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

user.module.ts

@NgModule({
  declarations: [
    UserComponent,
    UserManageComponent,
    UserListComponent
  ],

  imports: [
    CommonModule,
    FormsModule,

    UserRouting,
    SharedModule
  ]
})

user.routing.ts

const routes: Routes = [
  { path: '', component: UserComponent, children: [
    { path: '', component: UserListComponent },
    { path: 'new', component: UserManageComponent },
    { path: ':id/edit', component: UserManageComponent }
  ]},
];

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

还有问题:

我期望我的应用程序路由做什么:

/users => not a valid route
/users/new => not a valid route

/admin/users => valid route
/admin/users/new => valid route
/admin => valid route (should render AdminComponent)

我不知道为什么,但是如果我输入/ users,应用程序呈现UserComponent,那不是我想要的行为。

我希望只能从/ admin / users访问UserComponent。

有人能解释我为什么吗?

2 个答案:

答案 0 :(得分:1)

您是否已按照建议here尝试将AppRouting导入移至导入结束数组?

答案 1 :(得分:1)

试试看:

admin.routing.ts

const routes: Routes = [
  { path: 'admin', component: AdminComponent, canActivate: [AuthGuard], 
        children: [{ path: 'users', loadChildren: () => UserModule }]}
];