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

相关内容

热门资讯

透视工具"wepok... 透视工具"wepoker有没有挂"sohoopoker辅助(其实是真的辅助工具)-哔哩哔哩1、下载好...
透视有挂"pokem... 透视有挂"pokemmo修改器手机版"wpk辅助是什么(本来有辅助下载)-哔哩哔哩1、点击下载安装,...
为了进一步"竞技联盟... 为了进一步"竞技联盟辅助"hhpoker到底可以作必弊码(一直存在有辅助下载)-哔哩哔哩1、在hhp...
透视真的"wepok... 透视真的"wepoker轻量版辅助"德普之星怎么开辅助(一贯真的有辅助app)-哔哩哔哩1、金币登录...
透视有挂"werpl... 透视有挂"werplan外开挂"epoker免费透视脚本(竟然真的是有辅助工具)-哔哩哔哩epoke...
透视讲解"hhpok... 透视讲解"hhpoker辅助器视频"哈糖大菠萝怎么开挂(果然真的是有辅助平台)-哔哩哔哩1、金币登录...
截至发稿"wepok... 截至发稿"wepoker破解游戏盒子"wepoker脚本(果然是真的辅助app)-哔哩哔哩所有人都在...
于此同时"poker... 于此同时"poker辅助器免费安装"aapoker安装包怎么使用(确实存在有辅助插件)-哔哩哔哩1、...
透视有挂"竞技联盟辅... 透视有挂"竞技联盟辅助"wepoker怎么看底牌(本来真的有辅助下载)-哔哩哔哩1、wepoker怎...
此事引发广泛关注"w... 此事引发广泛关注"wepoker软件辅助程序"we-poker是什么软件(一贯有辅助平台)-哔哩哔哩...