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

相关内容

热门资讯

透视科技!红龙poker辅助工... 透视科技!红龙poker辅助工具(透视)竟然真的有挂(详细辅助可靠教程)1、红龙poker辅助透视辅...
透视ai代打!aapoker辅... 透视ai代打!aapoker辅助插件工具(透视)原来真的是有挂(详细辅助必备教程)1)aapoker...
透视模拟器!wepoker有人... 透视模拟器!wepoker有人用过吗(透视)真是有挂(详细辅助2025新版教程)1、每一步都需要思考...
透视计算!pokermaste... 透视计算!pokermaster破解版(透视)一直是有挂(详细辅助必胜教程)1、玩家可以在软件透明挂...
透视教程!wepoker破解器... 透视教程!wepoker破解器激活码(透视)一直真的是有挂(详细辅助攻略教程)1)辅助挂:进一步探索...
透视ai代打!wepoker买... 透视ai代打!wepoker买钻石有用吗(透视)切实是有挂(详细辅助2025新版)1、起透看视 透明...
透视代打!wepoker透视脚... 透视代打!wepoker透视脚本免费下载(透视)果然是真的有挂(详细辅助必胜教程);1、wepoke...
透视攻略!hhpoker的辅助... 透视攻略!hhpoker的辅助是真的吗(透视)其实是有挂(详细辅助新版2025教程)1、完成透视辅助...
透视攻略!wepoker透视脚... 透视攻略!wepoker透视脚本免费下载pc(透视)竟然存在有挂(详细辅助教你攻略);1)wepok...
透视插件!聚星ai辅助工具下载... 透视插件!聚星ai辅助工具下载(透视)原来真的有挂(详细辅助揭秘教程);辅助器中分为三种模型:软件透...