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

相关内容

热门资讯

透视私人局!wepoker分析... 透视私人局!wepoker分析,wepoker怎么挂飞机(透视)扑克教程(有挂黑科技)1、下载好we...
透视总结!wepoker买脚本... 透视总结!wepoker买脚本靠谱吗,wepoker手机版透视脚本(透视)专业教程(有挂详情)1、点...
透视新版!wepoker怎么挂... 透视新版!wepoker怎么挂底牌,wepoker免费透视(透视)可靠技巧(有挂规律);1、下载好w...
透视智能ai!wepoker怎... 透视智能ai!wepoker怎么看牌型,wepoker祈福有用吗(透视)新2025教程(有挂技巧)所...
透视教程!wepoker有辅助... 透视教程!wepoker有辅助功能吗,wepokerplus万能挂(透视)技巧教程(有挂黑科技)1、...
透视辅助!wepoker辅助器... 透视辅助!wepoker辅助器官方,wepoker辅助器软件下载(透视)技巧教程(有挂插件);一、w...
透视游戏!wepoker私人局... 透视游戏!wepoker私人局透视方法,wepoker手机插件(透视)2025新版教程(有挂插件)w...
透视攻略!wepoker有没有... 透视攻略!wepoker有没有挂,we-poker辅助(透视)详细教程(有挂解说)1、每一步都需要思...
透视模拟器!wepoker插件... 透视模拟器!wepoker插件下载,wepoker有辅助工具吗(透视)安装教程(有挂介绍);进入游戏...
透视挂透视!wepoker俱乐... 透视挂透视!wepoker俱乐部辅助,wepoker可以透视码(透视)德州论坛(有挂方法)1、wep...