本文介绍了路由到具有多个参数的相同组件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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,并且 url 应该如下所示

My objective is to route to HomeComponent with differnt Values and the url should look like

http://localhost:4200/#/home/env1 --> 路由到 HomeComponent,参数值为 env1

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 --> 路由到 HomeComponent,参数值为 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.

这篇关于路由到具有多个参数的相同组件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-30 22:54