Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular2 two routes to one component?

In Angular 2 I would like to define two routes, which use the same Component, but one route being a special case using a special preset parameter. Now what I want to do is his:

@RouteConfig([
  { path: '/',  name: 'Home', component: HomeComponent    },
  { path: '/user/:id', name: 'User', component: UserComponent  },
  { path: '/special-user', name: 'User', component: UserComponent, params:{'userId':'123'}  },
])

The thing I need is "params" in the last route-definition to "/special-user". Is this possible at all?

Edit: in the path /user/:id the id is part of the url, but in the special-user-case I would like for the id to be invisible and not to be part of the url

like image 488
Tobias Gassmann Avatar asked Dec 15 '22 06:12

Tobias Gassmann


2 Answers

Angular 2 Beta.x

Define route as

@RouteConfig([ 
  ...
  { path: '/special-user/:userId', name: 'SpecUser', component: UserComponent}
])

Use

inside template

[routerLink]="['SpecUser', {userId:123}]"

inside component

export class SomeComponent  {
  constructor(private router: Router) {}

  someMethod() {
    this.router.navigate(['SpecUser', {userId:123}]);
  }
}

Angular 2 RC

Define route as

@Routes([ 
  ...
  { path: '/special-user/:userId', component: UserComponent}
])

Use

inside template

[routerLink]="['/special-user', 123]"

inside component

export class SomeComponent  {
  constructor(private router: Router) {}

  someMethod() {
    this.router.navigate(['/special-user', 123]);
  }
}
like image 119
tchelidze Avatar answered Dec 18 '22 12:12

tchelidze


I have found the answer in this article:

https://auth0.com/blog/2016/01/25/angular-2-series-part-4-component-router-in-depth/1

configure the route

@RouteConfig([
  { path: '/myroute', component: MyComponent, name: 'MyRoute', data: { isAdmin: true } }
])

inside the component:

import {RouteData} from 'angular2/router';

export class MyComponent {
  isAdmin: boolean;

  constructor(data: RouteData) {
    this.isAdmin = data.get('isAdmin');
  }
}
like image 41
Tobias Gassmann Avatar answered Dec 18 '22 11:12

Tobias Gassmann