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

相关内容

热门资讯

脚本解迷!hh poker辅助... 脚本解迷!hh poker辅助器先试用,hhpoker透视脚本(透视)一直是有工具(哔哩哔哩)1、进...
最新消息!wepoker作必弊... 最新消息!wepoker作必弊视频,微信小程序微乐内蒙破解器,普及透视(真实有挂)-哔哩哔哩1、玩家...
透视揭露!wpk有作必弊吗,w... 透视揭露!wpk有作必弊吗,wpk私人局有透视吗(透视)其实存在有教程(哔哩哔哩)1、下载好透视辅助...
透视总结!wpk作必弊,微乐科... 透视总结!wpk作必弊,微乐科技软件下载,解密脚本(有挂教程)-哔哩哔哩1、实时wpk作必弊透视辅助...
脚本曝光!wejoker辅助软... 脚本曝光!wejoker辅助软件价格,wepoker破解器有用吗(透视)原来存在有脚本(哔哩哔哩)1...
透视黑科技!哈糖大菠萝助手,微... 透视黑科技!哈糖大菠萝助手,微信微乐小程序辅助器免费安装,开挂脚本(详细教程)-哔哩哔哩1)哈糖大菠...
据悉!WePoKer辅助器,微... 据悉!WePoKer辅助器,微乐小程序免费黑科技,关于脚本(今日头条)-哔哩哔哩在进入WePoKer...
透视详细!aapoker发牌逻... 透视详细!aapoker发牌逻辑,aapoker透视脚本下载(透视)确实是真的教程(哔哩哔哩)1. ...
透视好友房!wepoker有插... 透视好友房!wepoker有插件吗,微乐家乡麻辣自建房,总结透视(有挂技巧)-哔哩哔哩在进入wepo...
脚本透视!wpk俱乐部怎么作必... 脚本透视!wpk俱乐部怎么作必弊,wpk系统是否存在作必弊行为(透视)总是真的是有插件(哔哩哔哩)1...