进入园子的博客后台,默认显示的是博文列表
为了给 main.js 减肥,路由中对编辑博文的 component 采用了懒加载(lazy load)的方式
export const POST_EDITING_ROUTES: Routes = [
{
path: '',
loadComponent:
() => import('@app/pages/post-editing/post-editing-v2.component').then(m => m.PostEditingV2Component),
},
];
但编辑博文是最常用的操作,准备预加载(preload)这个懒加载的 component
对应的路由有3层
app.routes.ts
export const routes: Routes = [
{
path: 'posts',
loadChildren: () => import('./pages/posts/posts.routes').then(m => m.POSTS_ROUTES),
}
]
posts.routes.ts
export const POSTS_ROUTES: Routes = [
{
path: '',
component: PostsEntryComponent,
children: [
{
path: 'edit',
loadChildren: () =>
import('../post-editing/post-editing.routes').then(m => m.POST_EDITING_ROUTES),
}
]
}
];
post-editing.routes.ts
export const POST_EDITING_ROUTES: Routes = [
{
path: '',
loadComponent:
() => import('@app/pages/post-editing/post-editing-v2.component').then(m => m.PostEditingV2Component),
},
];
参考 Optimize your Angular app's user experience with preloading strategies 实现了预加载
custom-preloading-strategy.ts
@Injectable({ providedIn: "root" })
export class CustomPreloadingStrategy extends PreloadingStrategy {
preload(route: Route, load: () => Observable<any>): Observable<any> {
return route.data?.preload === true ? load() : of(null);
}
}
app.config.ts 中添加 CustomPreloadingStrategy
provideRouter(
routes,
withPreloading(CustomPreloadingStrategy),
),
posts.routes.ts 与 post-editing.routes.ts 中都要添加 preload: true
posts.routes.ts
{
path: 'edit',
loadChildren: () =>
import('../post-editing/post-editing.routes').then(m => m.POST_EDITING_ROUTES),
data: {
preload: true,
}
}
post-editing.routes.ts
{
path: '',
loadComponent:
() => import('@app/pages/post-editing/post-editing-v2.component').then(m => m.PostEditingV2Component),
data: {
preload: true,
},
}
这里的 CustomPreloadingStrategy 只是实现了预 import('../post-editing/post-editing.routes')
与 import('@app/pages/post-editing/post-editing-v2.component')
,也就是预加载了对应 component 的 chunk js 文件,并没有执行这个 component 进行预热
angular 中对应的源码 router_preloader.ts#L148