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

相关内容

热门资讯

分享透视!哈糖大菠萝破解器!总... 分享透视!哈糖大菠萝破解器!总是存在有辅助脚本(证实有挂)-哔哩哔哩1、哈糖大菠萝破解器辅助器安装包...
关于透视!wepoker透视方... 关于透视!wepoker透视方法,wpk透视插件,指南教程(真的有挂)-哔哩哔哩小薇(辅助器软件下载...
解密透视!德州局透视脚本下载安... 解密透视!德州局透视脚本下载安装最新版本!一直一直都是有辅助app(真实有挂)-哔哩哔哩德州局透视脚...
分享透视!竞技联盟辅助插件,约... 分享透视!竞技联盟辅助插件,约局吧游戏挂,资料教程(证实有挂)-哔哩哔哩1、进入到竞技联盟辅助插件是...
揭幕透视!pokermaste... 揭幕透视!pokermaster辅助器!确实有辅助技巧(新版有挂)-哔哩哔哩pokermaster辅...
有挂透视!wepoker作必弊... 有挂透视!wepoker作必弊辅助,pokerworld软件,机巧教程(有挂详细)-哔哩哔哩一、we...
详情透视!sohoo poke... 详情透视!sohoo poker辅助器!都是是有辅助神器(证实有挂)-哔哩哔哩1、金币登录送、破产送...
辅助透视!wpk作必弊,wpk... 辅助透视!wpk作必弊,wpk透视插件,模板教程(有挂实锤)-哔哩哔哩1、wpk透视插件免费脚本咨询...
必备透视!哈糖大菠萝开挂!本来... 必备透视!哈糖大菠萝开挂!本来真的是有辅助软件(了解有挂)-哔哩哔哩亲,关键说明,哈糖大菠萝开挂透视...
辅助透视!epoker有透视吗... 辅助透视!epoker有透视吗,wepoker私人局有透视吗,总结教程(有挂技巧)-哔哩哔哩1、we...