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、让任何用户...
透视解谜!wepoker怎么买... 透视解谜!wepoker怎么买辅助,wepoker手机插件-总是存在有辅助教程(哔哩哔哩)1、不需要...
透视曝光!wepoker提高好... 您好,这款游戏可以开挂的,确实是有挂的,需要了解加去威信【136704302】很多玩家在这款游戏中打...
透视总结!wepoker破解是... 透视总结!wepoker破解是真的还是假的,wepoker怎么增加运气-真是存在有辅助教程(哔哩哔哩...
透视揭幕!wepoker透视脚... 透视揭幕!wepoker透视脚本,wepoker免费脚本咨询-都是真的有辅助神器(哔哩哔哩)1、游戏...
透视专业!wepoker透视脚... 透视专业!wepoker透视脚本免费app,wepoker怎么挂底牌-一直一直总是有辅助插件(哔哩哔...
透视推荐!wpk透视辅助,wp... 透视推荐!wpk透视辅助,wpk安卓下载辅助-一贯有辅助插件(哔哩哔哩)1、用户打开应用后不用登录就...
透视有挂!购买的wpk辅助在哪... 您好,这款游戏可以开挂的,确实是有挂的,需要了解加去威信【485275054】很多玩家在这款游戏中打...
透视教你!wpk透视辅助方法,... 透视教你!wpk透视辅助方法,wpk插件-一贯是真的有辅助软件(哔哩哔哩)1、不需要AI权限,帮助你...
透视了解!aapoker怎么选... 透视了解!aapoker怎么选牌,aapoker透视脚本-原来一直都是有辅助app(哔哩哔哩)1、玩...