Angular(三) - 路由模块
程序员文章站
2024-01-14 12:02:04
...
在原始的路由配置中,你提供了仅有两个路由的简单配置来设置应用的路由。
如下图
对于简单的路由,这没有问题。 随着应用的成长,你用到了更多路由器特性,比如守卫、解析器和子路由
等,你会很自然地想要重构路由。
我们建议将路由信息移到一个单独的特殊用途的模块
,叫做 路由模块
路由模块有什么优点?
- 开发者可以很自然的从路由模块中查找和扩展路由配置
- 当设计复杂的守卫,解析等就会变得简单,一般而言你的项目都会使用守卫来验证是否登录,用子路由来实现页面中某一个局部的替换
典型的应用具有多个特性区,每个特性区都专注于特定的业务用途
在 /app
目录下创建一个名叫 app-routing.module.ts
的文件,以包含这个路由模块。
文件路径为 src/app/app-routing.module.ts
import { NgModule } from '@angular/core';
import { RouterModule, Routes } from '@angular/router';
import { CrisisListComponent } from './crisis-list.component';
import { HeroListComponent } from './hero-list.component';
import { PageNotFoundComponent } from './not-found.component';
const appRoutes: Routes = [
{ path: 'crisis-center', component: CrisisListComponent },
{ path: 'heroes', component: HeroListComponent },
{ path: '', redirectTo: '/heroes', pathMatch: 'full' },
{ path: '**', component: PageNotFoundComponent }
];
@NgModule({
imports: [
RouterModule.forRoot(
appRoutes,
{ enableTracing: true } // <-- debugging purposes only
)
],
exports: [
RouterModule
]
})
export class AppRoutingModule {}
修改原来配置 src/app/app.module.ts
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';
import { PageNotFoundComponent } from './not-found.component';
@NgModule({
imports: [
BrowserModule,
FormsModule,
AppRoutingModule
],
declarations: [
AppComponent,
HeroListComponent,
CrisisListComponent,
PageNotFoundComponent
],
bootstrap: [ AppComponent ]
})
export class AppModule { }
通过比较前后
app.module.ts
中的代码,我们仅仅是将 关于路由导航的部分移到app-routing.module.ts
, 同时将AppRoutingModule
向外exports ,然后在app.module.ts
中导入新建的路由模块
上一篇: angular中组件与服务一起使用
下一篇: lamp/lnmp优化1--缓存