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

时间:2018-07-23 15:20:36

标签: angular angular5 angular2-routing angular4-router

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,并且网址应类似于

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

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

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

有什么办法可以这样做吗?

1 个答案:

答案 0 :(得分:2)

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

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

以上内容将所有路由匹配到所有URL。这是通配符匹配的所有内容。它将首先在其后列出的路由之前进行匹配。