2 routes for one Angular component

3.2k Views Asked by At

I'm wondering is it possible to have 2 different routes that point to 1 single component? For example:

{ path: 'signin', component: SignInComponent },
{ path: 'tenant/:id/signin', component: SignInComponent }

I'm asking because I have some wired behaviour..

1

There are 1 best solutions below

6
On BEST ANSWER

Yes you can use 2 different route that point to the same component. But when you navigate from a route to a different route that uses the same component as the previous route then angular reuses your component instance. It does not create a new instance of your component.

If you will navigate from 'signin' to 'tenant/:id/signin' then angular will use the same instance of SignInComponent that it created for 'signin'. The constructor and init methods of SignInComponent will not be called. You can use observable in your init method. The params method of ActivatedRoute is a observable. You can do something like this to extract the parameter:

route is your ActivatedRoute instance

ngOnInit() {
  this.route.params
    .switchMap((params: Params) => this.service.getHero(+params['id']))
    .subscribe((hero: Hero) => this.hero = hero);
}

The switchMap operator allows you to perform an action with the current value of the Observable, and map it to a new Observable. This code gets a hero with id specified in the route from the service. You can do something like this. If you will post the code then I can tell you what exactly you need to do.