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

相关内容

热门资讯

传递经验!wepoker的辅助... 传递经验!wepoker的辅助器,wepoker能不能透视,攻略教程(有挂透明);亲真的是有正版授权...
三分钟了解!wepoker有没... 三分钟了解!wepoker有没有挂,wpk私人辅助,德州论坛(有挂透明);1分钟了解详细教程(微信 ...
盘点十款!约局吧如何查看是否有... 盘点十款!约局吧如何查看是否有挂,安装不了wepoker,规律教程(有挂软件);大神普及一款德州ai...
必备辅助推荐!hhpoker是... 必备辅助推荐!hhpoker是内部控制吗,红龙poker辅助,揭秘攻略(有挂技巧)1、不需要AI权限...
我来教教你!hhpoker到底... 我来教教你!hhpoker到底可以作弊码,wepoker私人局辅助,教你教程(有挂透视);人气非常高...
终于清楚!wpk透视是真的假的... 终于清楚!wpk透视是真的假的,aapoker透视插件,玩家教你(有挂透视)1、玩家可以在wpk透视...
必备攻略!wepoker轻量版... 必备攻略!wepoker轻量版有透视吗,来玩app破解版,2025新版(有挂软件);1.wepoke...
玩家必备攻略!德州局透视,德州... 玩家必备攻略!德州局透视,德州局脚本,科技教程(有挂攻略);最新版2024是一款经典耐玩的益智游戏,...
盘点一款!wepoker透视底... 盘点一款!wepoker透视底牌脚本,hhpoker有辅助吗,总结教程(有挂教程);玩家必备必赢加哟...
一分钟了解!wepoker有机... 一分钟了解!wepoker有机器人吗,wepoker好友局透视,2025新版教程(有挂透明)1、很好...