Search code examples
angularangular5angular2-routingangular4-router

Route to Same component with multiple Params


HTML Code

<button (click)='getEnv("env")'>environment</button>
<button (click)='getSchema("env","schema")'>schema</button>
<button (click)='getEvent("env","schema","event")'>event</button>

ROUTE FILE

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 CODE

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

}

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

http://localhost:4200/#/home/env1 --> routes to HomeComponent with param value as env1

http://localhost:4200/#/home/env1/schema1 --> routes to HomeComponent with param value as env1, schema1

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

but i prefer the format

http://localhost:4200/#/home/env/schema/event

Is there any way to do like this?


Solution

  • Remove the greedy path from the route list.

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

    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.