简体   繁体   中英

2 routes for one Angular component

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..

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM