angular+ 路由学习 (八)异步路由
- 使用 异步路由 来 解决应用的某些模块的懒加载,其优点:
- 你可以只在用户请求时才加载某些模块
- 对于只访问某一模块的用户,提高加载速度
- 减小初始加载的包体积,不管以后持续增加多少个懒加载模块
- 示例场景: 对于 adminModule 模块;只有已登录的用户才会用到,所以该模块可以使用懒加载;即AppModule在应用启动时就被加载,而该模块只有用户点击某个链接才会加载;
- 懒加载和重新配置工作只会在该路由首次被请求时加载一次;后续请求,该模块和路由都立即可使用;
- 将 admin-routing.module.ts 中
// 使用无组件路由,即分组路由,可以不需要用来只管理分组路由的组件 const adminRoutes: Routes = [ { // path: 'admin' 更改为 ''; path: '', component: AdminComponent, canActivate: [AuthGuard], children: [ { path: '', canActivateChild: [AuthGuard], children: [ { path: 'crises', component: ManageCrisesComponent}, { path: 'heroes', component: ManageHeroesComponent}, { path: '', component: AdminDashboardComponent} ] } ] } ];
- AppRoutingModule中
// loadChildren 接收函数;使用动态导入来懒加载代码;当代码请求并加载完毕后,这个promise会解析成一个NgModule 对象;即AdminModule const routes: Routes = [ { path: 'compose' , component: ComposeMessageComponent, outlet: 'popup'}, { path: 'admin', loadChildren: () => import('./admin/admin.module').then(mod => mod.AdminModule)}, { path: '', redirectTo: 'heroes', pathMatch: 'full' }, { path: '**', component: PageNotFoundComponent } ];
- 将该模块从主应用中分离开,在AppModule 中删除AdminModule
//... // import { AdminModule} from './admin/admin.module'; //... imports: [ BrowserModule, FormsModule, HeroesModule, CrisisCenterModule, // AdminModule, AuthModule, AppRoutingModule, BrowserAnimationsModule ], //....
- 使用CanLoad守卫 对该模块进行未授权加载保护,让只有登录用户才加载该模块
// auth.guard.ts 中 新增方法 // 路由器会将route 参数 设置为 准备访问的目标URL;如果用户登录,就会重定向到这个URL canLoad(route: Route): boolean { let url = `/${route.path}`; return this.checkLogin(url); }
- 将AuthGuard 导入AppRoutingModule.ts 中;并将AuthGuard 添加到admin 路由数组中
import { NgModule } from '@angular/core'; import { RouterModule, Routes } from '@angular/router'; import { ComposeMessageComponent } from './compose-message/compose-message.component'; import { PageNotFoundComponent } from './page-not-found/page-not-found.component'; import { AuthGuard } from './auth/auth.guard'; import { SelectivePreloadingStrategyService } from './selective-preloading-strategy.service'; const appRoutes: Routes = [ { path: 'compose', component: ComposeMessageComponent, outlet: 'popup' }, { path: 'admin', loadChildren: () => import('./admin/admin.module').then(mod => mod.AdminModule), canLoad: [AuthGuard] }, { path: 'crisis-center', loadChildren: () => import('./crisis-center/crisis-center.module').then(mod => mod.CrisisCenterModule), data: { preload: true } }, { path: '', redirectTo: '/superheroes', pathMatch: 'full' }, { path: '**', component: PageNotFoundComponent } ]; @NgModule({ imports: [ RouterModule.forRoot( appRoutes, { enableTracing: false, // <-- debugging purposes only preloadingStrategy: SelectivePreloadingStrategyService, } ) ], exports: [ RouterModule ] }) export class AppRoutingModule { }
想买的东西很贵,想去的地方很远,喜欢的女孩很完美