路由到具有多个参数的同一组件

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]);
  }

}

我的 objective 是路由到具有不同值的 HomeComponent 并且 url 应该看起来像

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

的 HomeComponent

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

http://localhost:4200/#/home/env1/schema1/event1 --> 路由到参数值为 env1、schema1 和 event1 的 HomeComponent

我知道我可以使用查询参数,但 url 看起来像

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

有什么办法可以这样吗?

从路由列表中删除贪心路径。

{ path: '**', component: HomeComponent },

以上匹配所有 URL 的所有路由。这是一个通配符匹配一切。它会在它后面列出的路由之前被首先匹配。