在Angular中为具有相同路径名的不同基本href加载不同组件



我的角度应用程序中有以下路径,对于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中,您使用ActivatedRouteAPI来确定它是home还是create:

public BaseComponent {
public slug: string = undefined;
construct(private route: ActivatedRoute) { }
ngOnInit() {
this.slug = this.route.snapshot.url[0].path;
}
}

在html中,使用*ngIf显示homecreate组件:

<app-home *ngIf="slug == 'home'"></app-home>
<app-create *ngIf="slug == 'create'"></app-create>

最新更新