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 导致的路由匹配问题。

相关内容

热门资讯

透视辅助!hhpoker透视脚... 透视辅助!hhpoker透视脚本,wepoker透视版下载,我来教大家(有挂透明)1、这是跨平台的黑...
透视app!wpk透视辅助方法... 透视app!wpk透视辅助方法,德普之星辅助功能如何打开,传递经验(有挂规律)1、下载好wpk透视辅...
透视教学!hhpoker透视脚... 透视教学!hhpoker透视脚本视频,红龙poker透视,每日必看推荐(有挂教学);1、游戏颠覆性的...
透视软件!wpk透视脚本下载,... 透视软件!wpk透视脚本下载,hhpoker透视脚本下载,最新通报(有挂技巧);1、ai机器人多个强...
透视免费!hhpoker辅助器... 透视免费!hhpoker辅助器,德普之星辅助器,盘点一款(有挂规律)1、起透看视 透明视辅助2、随意...
透视辅助!德普之星辅助功能如何... 透视辅助!德普之星辅助功能如何打开,aapoker辅助挂,实测必看(有挂教学)1、很好的工具软件,可...
透视模拟器!智星德州有脚本吗,... 透视模拟器!智星德州有脚本吗,wepoker免费透视脚本,重大通报(有挂了解)1、任何ai辅助神器的...
透视美元局!aapoker辅助... 透视美元局!aapoker辅助插件工具下载,wepoker辅助器是真的的吗,最新技巧(有挂透明)1、...
透视透视挂!hhpoker万能... 透视透视挂!hhpoker万能辅助器,wepoker透视脚本,推荐十款(有挂技巧);1、机器人多个强...
透视模拟器!wpk透视辅助靠谱... 透视模拟器!wpk透视辅助靠谱吗,aapoker免费透视脚本,传递经验(有挂方法)1、让任何用户在无...