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、进入到微乐家乡麻...
最新通报!微乐小程序游戏破解器... 最新通报!微乐小程序游戏破解器,微信微乐游戏辅助器-果然真的有辅助app(有挂攻略)1、每一步都需要...
我来教大家!微乐小程序微乐辅助... 我来教大家!微乐小程序微乐辅助软件,微信小程序微乐辅助器app-一贯存在有辅助脚本(有挂教程)一、微...
记者爆料!微乐小程序微乐辅助软... 记者爆料!微乐小程序微乐辅助软件,微乐广西自建房免费黑科技下载-真是是有辅助挂(存在有挂)微乐小程序...
总算明白!微乐小程序脚本工具平... 总算明白!微乐小程序脚本工具平台,微信小程序微乐房间有挂吗-竟然真的是有辅助方法(讲解有挂)1、点击...
玩家必看教程!微乐小程序免费工... 玩家必看教程!微乐小程序免费工具,微乐小程序插件免费贴吧-总是有辅助app(有挂工具)1、全新机制【...
一秒答解!微乐小程序游戏破解器... 一秒答解!微乐小程序游戏破解器,微乐小程序辅助器出租-好像是真的有辅助挂(有挂方略)在进入微乐小程序...
实测分享!微乐家乡麻将辅助,微... 实测分享!微乐家乡麻将辅助,微乐降序自建房辅助app-好像是真的有辅助挂(有挂解密)微乐家乡麻将辅助...
传递经验!微乐小程序辅助工具,... 传递经验!微乐小程序辅助工具,微信微乐游戏苹果辅助器-真是是真的有辅助工具(有挂教学)暗藏猫腻,小编...
重大发现!小程序微乐游戏辅助器... 您好,小程序微乐游戏辅助器这款游戏可以开挂的,确实是有挂的,需要了解加去威信【136704302】很...