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

相关内容

热门资讯

脚本推荐!hhpoker有没有... 脚本推荐!hhpoker有没有作必弊辅助,hhpoker脚本下载(透视)好像真的有插件(哔哩哔哩)1...
透视关于!aa poker辅助... 透视关于!aa poker辅助,aapoker怎么设置抽水(透视)都是存在有脚本(哔哩哔哩)一、aa...
脚本教你!wpk辅助器是真的吗... 脚本教你!wpk辅助器是真的吗,wpk俱乐部有没有辅助(透视)本来是有方法(哔哩哔哩)1、实时透视辅...
脚本详情!德普之星app安卓版... 脚本详情!德普之星app安卓版破解版,德普之星透视辅助软件下载(透视)竟然有插件(哔哩哔哩)1、起透...
透视了解!德普之星私人局辅助器... 透视了解!德普之星私人局辅助器,德普之星辅助器app(透视)好像真的是有app(哔哩哔哩)1、下载好...
透视推荐!aapoker破解侠... 透视推荐!aapoker破解侠是真的吗,aapoker怎么提高中牌率(透视)确实真的有工具(哔哩哔哩...
脚本关于!aapoker脚本怎... 脚本关于!aapoker脚本怎么用,aapoker透视脚本(透视)本来是有技巧(哔哩哔哩)1、玩家可...
脚本了解!wpk可以作必弊吗,... 脚本了解!wpk可以作必弊吗,如何判断wpk辅助软件的真假(透视)总是是有神器(哔哩哔哩)1)辅助插...
脚本解谜!hhpoker德州有... 脚本解谜!hhpoker德州有挂吗,hhpoker透视工具(透视)切实真的有教程(哔哩哔哩)1、每一...
透视详细!wejoker辅助软... 透视详细!wejoker辅助软件视频,htx矩阵wepoker辅助(透视)本来真的是有神器(哔哩哔哩...