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

相关内容

热门资讯

透视ai"wepok... 透视ai"wepoker有用吗"详细辅助解密教程(轻量版书签透视);大神普及一款德州ai内幕,确定了...
透视透视"wepok... 透视透视"wepoker钻石怎么看底牌"详细辅助2025教程(私人局透视教程技巧);玩家必备必赢加哟...
透视智能ai"wep... 透视智能ai"wepoker私人局俱乐部"详细辅助曝光教程(黑侠破解辅助)是一款可以让一直输的玩家,...
透视神器"wepok... 透视神器"wepoker透视挂底牌"详细辅助新2025版(是有挂软件软件)关于wepoker透视挂底...
透视系统"福建大菠萝... 1、透视系统"福建大菠萝万能辅助器"详细辅助科技教程(可以挂底牌透明)。2、福建大菠萝万能辅助器透视...
透视有挂"wepok... 1、透视有挂"wepoker辅助器激活码"详细辅助2025版教程(底牌透视神器)。2、wepoker...
透视ai代打"wep... 1、透视ai代打"wepoker高级辅助"详细辅助实用技巧(高级辅助神器)(UU poker、wep...
透视黑科技"hhpo... 透视黑科技"hhpoker软件可以玩吗"详细辅助插件教程(私人局外卦软件)1、许多玩家不知道hhpo...
透视能赢"哈糖大菠萝... 透视能赢"哈糖大菠萝万能挂"详细辅助玩家教你(辅助器v3.3教程);原来确实真的有挂(需添加指定薇1...
透视好友"hhpok... 透视好友"hhpoker作弊码"详细辅助黑科技教程(轻量版辅助软件)是一款可以让一直输的玩家,快速成...