在/app
目录新建一个文件,名叫app-routing.module.ts
。路由模块将导入RouterModule
令牌,并配置路由。 我们遵循文件名约定,并命名Angular模块为AppRoutingModule
。
和app.module.ts
中一样,导入CrisisListComponent
和HeroListComponent
组件。 然后在路由模块中导入Router
和路由配置(RouterModule.forRoot
)。
同时导出AppRoutingModule
,这样我们可以将它添加到AppModule
的imports
中。
最后,重新导出RouterModule
,这样,特征模块在使用路由模块时,将获得路由指令。
下面是首个路由模块:
app/app-routing.module.ts (excerpt)
import { NgModule } from '@angular/core';
import { RouterModule, Routes } from '@angular/router';
import { CrisisListComponent } from './crisis-list.component';
import { HeroListComponent } from './hero-list.component';
const appRoutes: Routes = [
{ path: 'crisis-center', component: CrisisListComponent },
{ path: 'heroes', component: HeroListComponent }
];
@NgModule({
imports: [
RouterModule.forRoot(appRoutes)
],
exports: [
RouterModule
]
})
export class AppRoutingModule {}
接下来,我们将更新app.module.ts
文件,从app-routing.module.ts
中导入AppRoutingModule
令牌, 并用它替换RouterModule.forRoot
。
app/app.module.ts (excerpt)
import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { FormsModule } from '@angular/forms';
import { AppComponent } from './app.component';
import { AppRoutingModule } from './app-routing.module';
import { CrisisListComponent } from './crisis-list.component';
import { HeroListComponent } from './hero-list.component';
@NgModule({
imports: [
BrowserModule,
FormsModule,
AppRoutingModule
],
declarations: [
AppComponent,
HeroListComponent,
CrisisListComponent
],
bootstrap: [ AppComponent ]
})
export class AppModule {
}
应用继续正常运行,我们可以把路由模块作为为每个特征模块维护路由配置的中心地方