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

相关内容

热门资讯

解密透视!aapoker怎么控... 解密透视!aapoker怎么控制牌,微乐小程序游戏破解器下载,诀窍教程(有挂教学)-哔哩哔哩小薇(辅...
专业透视!智星菠萝辅助,微乐家... 专业透视!智星菠萝辅助,微乐家乡官方app下载,举措教程(有挂秘诀)-哔哩哔哩1、操作简单,无需智星...
普及透视!wpk辅助器,提高微... 普及透视!wpk辅助器,提高微乐运气的方法,资料教程(确实有挂)-哔哩哔哩1、操作简单,无需wpk辅...
必备透视!德州透视是真的假的,... 您好,德州透视是真的假的这款游戏可以开挂的,确实是有挂的,需要了解加去威信【485275054】很多...
解迷透视!wpk德州局怎么透视... 解迷透视!wpk德州局怎么透视,微信微乐游戏辅助脚本,项目教程(讲解有挂)-哔哩哔哩wpk德州局怎么...
解密透视!wepoker养号规... 解密透视!wepoker养号规律,微乐南昌辅助神器,资料教程(有挂秘籍)-哔哩哔哩运wepoker养...
详细透视!wepoker国外版... 详细透视!wepoker国外版透视,微信微乐辅助ios,大纲教程(有挂神器)-哔哩哔哩1、wepok...
必备透视!大菠萝辅助器,微乐小... 必备透视!大菠萝辅助器,微乐小程序礼包码,烘培教程(有挂解密)-哔哩哔哩1、实时大菠萝辅助器透视辅助...
关于透视!拱趴大菠萝开挂方法,... 关于透视!拱趴大菠萝开挂方法,微信小程序游戏破解微乐辅助,举措教程(真的有挂)-哔哩哔哩1、完成拱趴...
普及透视!wepoker插件程... 普及透视!wepoker插件程序激活码,微乐麻将自建房app,策略教程(有挂技术)-哔哩哔哩wepo...