简体   繁体   English

一个Angular组件的2条路由

[英]2 routes for one Angular component

I'm wondering is it possible to have 2 different routes that point to 1 single component? 我想知道是否有可能有2个不同的路由指向1个单一组件? 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. 是的,您可以使用指向同一组件的2种不同路线。 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. 但是,当您从路径导航到使用与先前路径相同的组件的其他路径时,angular会重新使用您的组件实例。 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'. 如果你将从'signin'导航到'tenant /:id / signin',那么angular将使用它为'signin'创建的相同的SignInComponent实例。 The constructor and init methods of SignInComponent will not be called. 不会调用SignInComponent的构造函数和init方法。 You can use observable in your init method. 您可以在init方法中使用observable。 The params method of ActivatedRoute is a observable. ActivatedRoute的params方法是可观察的。 You can do something like this to extract the parameter: 您可以执行以下操作来提取参数:

route is your ActivatedRoute instance route是你的ActivatedRoute实例

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. switchMap运算符允许您使用Observable的当前值执行操作,并将其映射到新的Observable。 This code gets a hero with id specified in the route from the service. 此代码获取具有在来自服务的路由中指定的id的英雄。 You can do something like this. 你可以做这样的事情。 If you will post the code then I can tell you what exactly you need to do. 如果您要发布代码,那么我可以告诉您具体需要做什么。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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