我的主模块路由中有这样的路由。
const routes: Routes = [
{
path: '',
redirectTo: 'home',
pathMatch: 'full',
},
{
path: 'home',
component: MainComponent,
children: [
{
path: '',
loadChildren: () => import('../HR/human-resources.module').then(m => m.HumanResourcesModule),
}
]
}];
在 human-resources-routing.module.ts 中我有这样的路由。
const routes: Routes = [
{
path: '',
children: [
{
path: '',
component: QuestionGroupComponent
},
{
path: 'reports',
component: DatePeriodComponent
},
{
path: 'states',
component: StateWithTopPersonnelComponent
},
{
path: 'personnel',
component: StatePersonnelComponent
},
{
path: 'personnel-detail',
component: PersonnelDetailComponent
}
]
}];
例如,现在当我想要转到 DatePeriodComponent 时,我有一个像这样的 URL http://localhost:4200/home/reports 但我想要显示的内容有点不同。 我想显示像这样的 URL http://localhost:4200/reports ,但我的所有路由都没有 home 。我怎样才能省略它或防止在 URL 中显示?
最佳答案
我认为解决这个问题的一种方法是使用自定义 UrlSerializer
.
DefaultUrlSerializer
是 UrlSerializer
的默认实现例如, Router.parseUrl()
使用它方法:
urlTree = this.urlSerializer.parse(url);
或者当setting the browser's URL时(这可能是您的问题所需要的):
private setBrowserUrl(
url: UrlTree, replaceUrl: boolean, id: number, state?: {[key: string]: any}) {
const path = this.urlSerializer.serialize(url);
state = state || {};
if (this.location.isCurrentPathEqualTo(path) || replaceUrl) {
// TODO(jasonaden): Remove first `navigationId` and rely on `ng` namespace.
this.location.replaceState(path, '', {...state, navigationId: id});
} else {
this.location.go(path, '', {...state, navigationId: id});
}
}
URL 是 UrlTree
的序列化版本。结果,UrlTree
是 URL 的反序列化版本。 DefaultUrlSerializer
使用 UrlParser
反序列化 URL 字符串:
parse(url: string): UrlTree {
const p = new UrlParser(url);
return new UrlTree(p.parseRootSegment(), p.parseQueryParams(), p.parseFragment());
}
因此,解决此问题的方法是提供 UrlSerializer
的自定义实现:
// In `providers` array
{ provide: UrlSerializer, useClass: CustomImplOfUrlSerializer },
一个可能的(也是基本的)实现可能是使用改变 DefaultUrlSerializer.serialize(urlTree)
的返回值在CustomImplOfUrlSerializer.serialize(urlTree)
,通过替换 /home
与 ''
:
class CustomImplOfUrlSerializer implements UrlSerializer {
serialize (urlTree: UrlTree): string {
const raw = (new DefaultUrlSerializer()).serialize(urlTree);
return raw.replace('/home', '')
}
}
此外,如果您想了解更多有关 UrlTree
的信息,以及为什么它有用,我建议查看 this article .
关于angular - 浏览器 URL 中显示所需的路线,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64302359/