我的角度应用程序中有以下路径,对于home
,path base href设置为/home/
,对于创建/create/
http://localhost:3000/home/account
https://localhost:3000/create/account
动态路由配置路径,
export const AppRoute = {
'homeRoutes': [
{ path: 'account', loadChildren: () => import('@home').then(m => m.HomeModule) },
{ path: 'test', loadChildren: () => import('@test').then(m => m.TestModule) },
{ path: '**', component: PageNotFoundComponent }
],
'createRoutes': [
{ path: 'account', loadChildren: () => import('@create').then(m => m.CreateModule) },
{ path: 'login-test', loadChildren: () => import('@logintest').then(m => m.LoginTestModule) },
{ path: '**', component: PageNotFoundComponent }
]
};
在AppComponent.ts中
resetRouter () {
const baseHref = this.platformLocation.getBaseHrefFromDOM();
if (baseHref.match('/home/')) {
this.router.resetConfig(routes.homeRoutes);
}
if (baseHref.match('/create/')) {
this.router.resetConfig(routes.createRoutes);
}
}
在路由模块
const routes = [
{ path: 'home/account', loadChildren: () => import('@home').then(m => m.HomeModule) },
{ path: 'create/account', loadChildren: () => import('@home').then(m => m.HomeModule) },
{ path: 'test', loadChildren: () => import('@test').then(m => m.TestModule) },
{ path: 'login-test', loadChildren: () => import('@logintest').then(m => m.LoginTestModule) },
{ path: 'page-not-found', component: PageNotFoundComponent }
];
所以现在的问题是,
我的应用程序现在只能在http://localhost:3000/home/home/account
中访问,这是不期望的。
此外,如果访问create
路由f.ehttp://localhost:3000/home/test
有效,但实际期望是抛出错误页面。
请帮我配置这些路由。
我会改变你的方法。由于路由配置只是一个常量,您可以通过将映射的数组拆包到routes
常量中来复制两者的路由配置(见此答案(:
const routes = [
...['home', 'create'].map(path => ({
path: path,
component: BaseComponent,
loadChildren: () => import('@home').then(m => m.HomeModule)
})),
{ path: 'test', loadChildren: () => import('@test').then(m => m.TestModule) },
{ path: 'login-test', loadChildren: () => import('@logintest').then(m => m.LoginTestModule) },
{ path: 'page-not-found', component: PageNotFoundComponent }
];
然后在BaseComponent.ts
中,您使用ActivatedRoute
API来确定它是home
还是create
:
public BaseComponent {
public slug: string = undefined;
construct(private route: ActivatedRoute) { }
ngOnInit() {
this.slug = this.route.snapshot.url[0].path;
}
}
在html中,使用*ngIf
显示home
或create
组件:
<app-home *ngIf="slug == 'home'"></app-home>
<app-create *ngIf="slug == 'create'"></app-create>