Angular对某些路由移除了base-href。
创始人
2024-10-24 15:31:41
0

在使用 Angular 路由时需要注意,如果在根模块中设置了 base-href,在使用 loadChildren 懒加载模块时会移除这个 base-href,导致路由无法正确匹配。因此需要在懒加载模块中重新设置 base-href。

示例代码:

// app.module.ts @NgModule({ imports: [ CommonModule, RouterModule.forRoot(routes, { initialNavigation: 'enabled', relativeLinkResolution: 'legacy', }), ], }) export class AppModule {}

// lazy.module.ts @NgModule({ imports: [ CommonModule, RouterModule.forChild([ { path: '', component: LazyComponent, children: [ { path: 'child', component: LazyChildComponent, data: { baseHref: '/lazy', }, }, ], }, ]), ], }) export class LazyModule { constructor( private router: Router, private activatedRoute: ActivatedRoute ) { this.router.events .pipe(filter((e) => e instanceof NavigationEnd)) .subscribe(() => { const { root } = this.activatedRoute; const { baseHref } = root.firstChild.snapshot.data; if (baseHref) { const base = document.createElement('base'); base.href = baseHref; const head = document.getElementsByTagName('head')[0]; head.insertBefore(base, head.firstChild); } }); } }

上述代码中,我们在路由配置中加入了一个 data 属性,用来存储每个子路由需要设置的 base-href。在 LazyModule 的 constructor 中通过订阅路由事件,在路由变化时手动插入新增的 base 标签来设置 base-href。这个方法可以避免 Angular 移除 base-href 导致的路由匹配问题。

相关内容

热门资讯

外挂诀窍!德州机器人代打脚本,... 外挂诀窍!德州机器人代打脚本,智星菠萝可以辅助吗-本来是有辅助技巧(哔哩哔哩)暗藏猫腻,小编详细说明...
外挂积累!xpoker辅助,线... 外挂积累!xpoker辅助,线上德州的辅助器是什么-好像一直总是有辅助工具(哔哩哔哩)1)线上德州的...
外挂教材!德州辅助工具到底怎么... 外挂教材!德州辅助工具到底怎么样,竞技联盟透视-一贯一直总是有辅助神器(哔哩哔哩)1、游戏颠覆性的策...
外挂演示!xpoker透视辅助... 外挂演示!xpoker透视辅助,pokemomo辅助工具-都是一直总是有辅助方法(哔哩哔哩)1、这是...
外挂演示!智星德州插件2024... 外挂演示!智星德州插件2024最新版,哈糖大菠萝辅助器-本来真的有辅助脚本(哔哩哔哩)智星德州插件2...
外挂办法!pokernow辅助... 外挂办法!pokernow辅助工具,poker master辅助-原来一直都是有辅助攻略(哔哩哔哩)...
外挂方案!智星菠萝德州插件怎么... 外挂方案!智星菠萝德州插件怎么下载,智星德州辅助译码插件靠谱吗-一直有辅助方法(哔哩哔哩)1、下载好...
外挂窍门!哈糖大菠萝怎么开挂,... 外挂窍门!哈糖大菠萝怎么开挂,德普之星透视辅助软件-原来是真的有辅助app(哔哩哔哩)小薇(辅助器软...
外挂法子!德州局透视脚本,来玩... 外挂法子!德州局透视脚本,来玩app破解版-果然是真的有辅助软件(哔哩哔哩)1.德州局透视脚本 选牌...
外挂诀窍!约局吧德州真的有透视... 外挂诀窍!约局吧德州真的有透视挂吗,xpoker辅助助手-本来真的有辅助技巧(哔哩哔哩)1、全新机制...