首页 新闻 会员 周边 捐助

angular 中如何预加载懒加载的 standalone component

0
悬赏园豆:30 [已解决问题] 浏览: 27次 解决于 2025-02-02 12:14

进入园子的博客后台,默认显示的是博文列表

为了给 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),   
    },
];
dudu的主页 dudu | 高人七级 | 园豆:27977
提问于:2025-02-01 19:16
< > 人人可用的开源BI工具
分享
最佳答案
0

参考 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 进行预热

dudu | 高人七级 |园豆:27977 | 2025-02-02 11:16

angular 中对应的源码 router_preloader.ts#L148

dudu | 园豆:27977 (高人七级) | 2025-02-02 12:10
清除回答草稿
   您需要登录以后才能回答,未注册用户请先注册
Top