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

相关内容

热门资讯

据监测!wepokerplus... 据监测!wepokerplus到底是挂了吗(透视)微信小程序微乐辅助器贴吧(总是有辅助教程)-哔哩哔...
透视辅助!wepoker透视功... 透视辅助!wepoker透视功能下载(透视)微乐小程游戏破解器下载(好像存在有辅助工具)-哔哩哔哩1...
做出回应!wepoker能不能... 做出回应!wepoker能不能透视(透视)微乐辅助软件购买平台(一贯真的有辅助挂)-哔哩哔哩1、每一...
攻略辅助挂!哈糖大菠萝辅助器(... 攻略辅助挂!哈糖大菠萝辅助器(透视)微乐家乡官方免费下载安装(其实存在有辅助方法)-哔哩哔哩哈糖大菠...
近年来!pokemmo修改器手... 近年来!pokemmo修改器手机版(透视)微乐家乡app辅助器(好像是真的辅助神器)-哔哩哔哩1、p...
现就发布提示!wepoker透... 现就发布提示!wepoker透视最简单三个步骤(透视)微乐宁夏小程序插件(竟然是有辅助脚本)-哔哩哔...
透视辅助!哈糖大菠萝开挂(透视... 透视辅助!哈糖大菠萝开挂(透视)微乐广西小程序(一直存在有辅助app)-哔哩哔哩1、透视辅助!哈糖大...
经调查!wepoker软件安装... 经调查!wepoker软件安装包(透视)微乐卡五星祈福有用吗(竟然是真的辅助方法)-哔哩哔哩1、让任...
据玩家消息!hhpoker透视... 据玩家消息!hhpoker透视脚本(透视)微乐小程序游戏破解器(其实有辅助插件)-哔哩哔哩在进入hh...
为了进一步!wepoker透视... 为了进一步!wepoker透视脚本免费app(透视)微信小程序辅助器脚本(果然是真的辅助神器)-哔哩...