3

我在我的應用程序下面的路由配置:路由和模塊

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。

有人可以解釋我爲什麼嗎?

+0

因爲你要重定向一切管理:'{路徑: '',redirectTo: '管理員',pathMatch: '全'}' – jonrsharpe

+0

這不是問題。即使我刪除了這條路徑,該應用程序仍然無法按預期工作。 /用戶不應該可用,但/ admin/users。 –

+0

[樣式指南](https://angular.io/guide/styleguide#style-02-12)的獎勵:*使用'-routing.module.ts' *結束RoutingModule的文件名*(CLI將會爲你做這個) – Leo

回答

1

您是否已經嘗試將AppRouting導入移動到導入數組結尾?

1

試試這個看:

admin.routing.ts 

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