动态 angular 路由器路径
Dynamic angular router path
这是我当前的路由器:
const routes: Routes = [
{ path: '', component: HomeComponent },
{ path: 'filter', component: FiltersPageComponent},
{ path: 'filter/:continent', component: FiltersPageComponent},
{ path: '**', canActivate: [RouteLoader], component: ErrorComponent},
];
我有一个动态 url 是在用户搜索多个目的地时创建的。
url 示例:localhost:4200/filter/africa/botswana/europe/spain/asia/china
我可以创建 1 个接受此 url 的路径而不创建如下所示的多个路径吗?
{ path: 'filter/:test/:test2/:test3/:test4/:test5/:test6', component: FiltersPageComponent}
不,你不能。您的路线中不能有重复的参数。如果你这样做,你只能得到最后一个在url中有重复的数据。在您的情况下,它将 return 仅亚洲和中国
Angular 的 paramMap
应该启用它。
您可以分别订阅url参数和运行您想要的每条路线。请参见下面的示例:
this.route.paramMap.subscribe(params => {
if (params.get('username'))) {
// Route to particular path...
// Or do something else...
}
});
这里有一些额外的资源:
使用 path
参数是不可能的(也是错误的),但是你应该可以使用 query
参数来做到这一点:
localhost:4200/yourroute?filter=africa&filter=botswana&filter=europe&filter=spain
我最终使用的解决方案是这样的:
{ path: 'filter', component: FiltersPageComponent,
children: [
{ path: '**', component: FiltersPageComponent}
]
},
我在使用这种方法时唯一能想到的问题是,用户可以在 url 中的 filter/ 之后随意放置任何内容,它仍然会重定向到 filtersPageComponent。
这是我当前的路由器:
const routes: Routes = [
{ path: '', component: HomeComponent },
{ path: 'filter', component: FiltersPageComponent},
{ path: 'filter/:continent', component: FiltersPageComponent},
{ path: '**', canActivate: [RouteLoader], component: ErrorComponent},
];
我有一个动态 url 是在用户搜索多个目的地时创建的。
url 示例:localhost:4200/filter/africa/botswana/europe/spain/asia/china
我可以创建 1 个接受此 url 的路径而不创建如下所示的多个路径吗?
{ path: 'filter/:test/:test2/:test3/:test4/:test5/:test6', component: FiltersPageComponent}
不,你不能。您的路线中不能有重复的参数。如果你这样做,你只能得到最后一个在url中有重复的数据。在您的情况下,它将 return 仅亚洲和中国
Angular 的 paramMap
应该启用它。
您可以分别订阅url参数和运行您想要的每条路线。请参见下面的示例:
this.route.paramMap.subscribe(params => {
if (params.get('username'))) {
// Route to particular path...
// Or do something else...
}
});
这里有一些额外的资源:
使用 path
参数是不可能的(也是错误的),但是你应该可以使用 query
参数来做到这一点:
localhost:4200/yourroute?filter=africa&filter=botswana&filter=europe&filter=spain
我最终使用的解决方案是这样的:
{ path: 'filter', component: FiltersPageComponent,
children: [
{ path: '**', component: FiltersPageComponent}
]
},
我在使用这种方法时唯一能想到的问题是,用户可以在 url 中的 filter/ 之后随意放置任何内容,它仍然会重定向到 filtersPageComponent。