路由到具有多个参数的同一组件 [英] Route to Same component with multiple Params
问题描述
HTML代码
<button (click)='getEnv("env")'>environment</button>
<button (click)='getSchema("env","schema")'>schema</button>
<button (click)='getEvent("env","schema","event")'>event</button>
路线文件
export const ROUTES: Routes = [
{ path: '', redirectTo: 'home',pathMatch:"full" },
//{ path: 'home', component: HomeComponent },
{ path: 'example', component: ExampleComponent },
{ path: '**', component: HomeComponent },
{ path: 'home/:env', component: HomeComponent,pathMatch:'full' },
{ path: 'home/:env/:schema', component: HomeComponent,pathMatch:'full' },
{ path: 'home/:env/:schema/:event', component: HomeComponent,pathMatch:'full' }
TS代码
export class HomeComponent {
environment: string;
schema: string;
event: string;
constructor(public tasksService: TasksService, private router: Router, private route: ActivatedRoute) {
this.router.paramsInheritanceStrategy = 'emptyOnly';
this.route.params.subscribe(p => {
this.environment=p[0];
this.schema=p[1],
this.event=p[2]
})
}
getEvent(_env: string, _schema: string, _event: string) {
this.router.navigate(['home',_env,_schema,_event]);
}
getSchema(_env: string, _schema: string) {
this.router.navigate(['home',_env, _schema]);
}
getEnv(_env: string) {
this.router.navigate(['home',_env]);
}
}
我的目标是使用不同的值路由到HomeComponent,并且网址应类似于
My objective is to route to HomeComponent with differnt Values and the url should look like
http://localhost:4200/#/home/env1 ->路由参数值为env1的HomeComponent
http://localhost:4200/#/home/env1 --> routes to HomeComponent with param value as env1
http://localhost:4200/#/home/env1/schema1 ->路由到参数为env1,schema1的HomeComponent
http://localhost:4200/#/home/env1/schema1 --> routes to HomeComponent with param value as env1, schema1
http://localhost:4200/#/home/env1/schema1/event1 ->路由到参数为env1,schema1&事件1
http://localhost:4200/#/home/env1/schema1/event1 --> routes to HomeComponent with param value as env1, schema1 & event1
我知道我可以使用查询参数,但是网址看起来像
I know i can use query parameters but the url will look like
http://localhost:4200/#/home?env = env1
http://localhost:4200/#/home?env = env1& ; schema = schema1
http://localhost:4200/#/home ?env = env1& schema = schema1& event = event1
但我更喜欢格式
http://localhost:4200/#/home/env/schema/event
有没有办法做这样的事?
Is there any way to do like this?
推荐答案
从路由列表中删除贪婪路径.
Remove the greedy path from the route list.
{ path: '**', component: HomeComponent },
以上内容将所有路由匹配到所有URL.这是通配符匹配的所有内容.它将首先在其后列出的路由之前进行匹配.
The above matches all routes to all URLs. It is a wildcard match everything. It will be matched first before the routes listed after it.
这篇关于路由到具有多个参数的同一组件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!