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

相关内容

热门资讯

8分钟诀窍!wepoker辅助... 您好,wepoker辅助器有哪些功能这款游戏可以开挂的,确实是有挂的,需要了解加去威信【485275...
四分钟法子!wpk透视是真的假... 四分钟法子!wpk透视是真的假的(透视)都是是有辅助神器(哔哩哔哩)wpk透视是真的假的辅助器是一种...
第七分钟总结!hhpoker有... 第七分钟总结!hhpoker有后台操作吗(透视)果然是有辅助教程(哔哩哔哩)1、该软件可以轻松地帮助...
第六分钟手段!黑侠破解wepo... 第六分钟手段!黑侠破解wepoker(透视)真是是有辅助辅助(哔哩哔哩)1、打开软件启动之后找到中间...
3分钟讲义!wepoker分析... 3分钟讲义!wepoker分析(透视)真是真的是有辅助教程(哔哩哔哩)1、这是跨平台的wepoker...
第1分钟妙招!poker wo... 第1分钟妙招!poker world辅助(透视)本来真的是有辅助开挂(哔哩哔哩)1、下载好poker...
第十分钟方式!wepokerp... 第十分钟方式!wepokerplus到底是挂了吗(透视)切实存在有辅助脚本(哔哩哔哩)1、操作简单,...
两分钟法子!hhpoker辅助... 两分钟法子!hhpoker辅助(透视)确实是有辅助开挂(哔哩哔哩)亲,关键说明,hhpoker辅助透...
第九分钟窍要!模拟器打开hhp... 第九分钟窍要!模拟器打开hhpoker(透视)竟然真的是有辅助开挂(哔哩哔哩)在进入模拟器打开hhp...
五分钟学习!wepoker有辅... 五分钟学习!wepoker有辅助功能吗(透视)总是存在有辅助神器(哔哩哔哩)1、wepoker有辅助...