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

相关内容

热门资讯

透视了解!wepokerplu... 透视了解!wepokerplus到底是挂了吗(透视)总是真的是有辅助下载(有挂总结)-哔哩哔哩1.w...
透视透视挂!pokemmo手机... 透视透视挂!pokemmo手机版修改器(透视)其实存在有辅助插件(有挂规律)-哔哩哔哩1、透视透视挂...
透视app!pokemmo内置... 透视app!pokemmo内置修改器(透视)原来真的有辅助软件(真是有挂)-哔哩哔哩1、金币登录送、...
透视辅助!wepoker开脚本... 透视辅助!wepoker开脚本视频(透视)一贯有辅助软件(了解有挂)-哔哩哔哩1、全新机制【wepo...
透视美元局!wpk安卓下载辅助... 透视美元局!wpk安卓下载辅助(透视)总是真的有辅助工具(有挂秘诀)-哔哩哔哩1、wpk安卓下载辅助...
透视透视!拱趴大菠萝辅助神器(... 透视透视!拱趴大菠萝辅助神器(透视)一贯真的有辅助神器(有挂透视)-哔哩哔哩1、拱趴大菠萝辅助神器透...
透视挂透视!wepoker轻量... 透视挂透视!wepoker轻量版透视(透视)果然有辅助插件(有挂分享)-哔哩哔哩1、透视挂透视!we...
截至发稿!智星德州插件最新版本... 截至发稿!智星德州插件最新版本更新内容详解(透视)其实存在有辅助插件(有挂方法)-哔哩哔哩1)智星德...
来临!sohoo竞技联盟辅助器... 来临!sohoo竞技联盟辅助器(透视)竟然是真的辅助app(有挂方针)-哔哩哔哩1、任何sohoo竞...
近年来!德州来玩辅助器(透视)... 近年来!德州来玩辅助器(透视)好像存在有辅助下载(今日头条)-哔哩哔哩1、完成德州来玩辅助器辅助器v...