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

相关内容

热门资讯

透视新版"德普之星私... 您好,德普之星私人局透视这款游戏可以开挂的,确实是有挂的,需要了解加微【136704302】很多玩家...
揭秘攻略!拱趴游戏破解器,we... 揭秘攻略!拱趴游戏破解器,wepokerplus万能挂,黑科技教程(有挂教程)1、点击下载安装,微扑...
透视辅助"wepok... 透视辅助"wepoker有没有挂"详细辅助必备教程(从来真的是有挂);小薇(透视辅助)致您一封信;亲...
实测发现!wepoker私局代... 实测发现!wepoker私局代打,xpoker辅助怎么用,透明教程(有挂攻略)1、不需要AI权限,帮...
透视存在"德州透视插... 透视存在"德州透视插件"详细辅助存在挂教程(固有真的有挂)1、玩家可以在德州透视插件软件透明挂俱乐部...
推荐十款!哈糖大菠萝挂,德普之... 推荐十款!哈糖大菠萝挂,德普之星透视,技巧教程(有挂透明)关于哈糖大菠萝挂机制的,其中提到了后台系统...
透视计算"wepok... 透视计算"wepoker俱乐部辅助"详细辅助切实教程(竟然存在有挂);支持多人共享记分板与复盘,通过...
玩家必看秘籍!hhpoker透... 玩家必看秘籍!hhpoker透视工具,哈糖大菠萝破解器,2025新版(有挂方法);1分钟了解详细教程...
透视好友"hhpok... 透视好友"hhpoker脚本下载"详细辅助2025新版教程(果然是真的有挂)准备好在hhpoker脚...
分享个大家!wepoker有辅... 分享个大家!wepoker有辅助插件吗,xpoker怎么作弊,线上教程(有挂辅助);实战中需综合运用...