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

相关内容

热门资讯

外挂手册!德普之星透视辅助插件... 外挂手册!德普之星透视辅助插件,sohoo竞技联盟辅助器-真是真的是有辅助插件(哔哩哔哩)1、完成s...
外挂技法!悦扑克脚本,佛手大菠... 外挂技法!悦扑克脚本,佛手大菠萝辅助-果然真的是有辅助教程(哔哩哔哩)1)佛手大菠萝辅助有没有挂:进...
外挂妙招!德普之星app安卓版... 外挂妙招!德普之星app安卓版破解版,智星菠萝可以辅助吗-果然是有辅助app(哔哩哔哩)暗藏猫腻,小...
外挂办法!poker worl... 外挂办法!poker world辅助,哈糖大菠萝万能挂-原来一直总是有辅助插件(哔哩哔哩);1、任何...
外挂办法!xpoker辅助,p... 外挂办法!xpoker辅助,pokerrrr2辅助-其实是有辅助软件(哔哩哔哩)1、pokerrrr...
外挂积累!poker mast... 外挂积累!poker master辅助,xpoker辅助工具-本来是有辅助技巧(哔哩哔哩)一、pok...
外挂课程!约局吧德州可以透视吗... 外挂课程!约局吧德州可以透视吗,德普之星怎么设置埋牌-本来一直总是有辅助技巧(哔哩哔哩)1、该软件可...
外挂模块!德普之星有辅助软件吗... 外挂模块!德普之星有辅助软件吗,pokerworld软件-竟然有辅助插件(哔哩哔哩)1、下载好pok...
外挂技法!红龙poker作必弊... 外挂技法!红龙poker作必弊指令,德普之星透视软件免费入口官网-真是是真的有辅助攻略(哔哩哔哩)1...
外挂方式!智星德州插件2024... 外挂方式!智星德州插件2024最新版,拱趴大菠萝万能挂图解-切实真的有辅助教程(哔哩哔哩)1、外挂方...