I have a separate module with a routing module imported into it, in which the routes look like:
const routes: Routes = [
{
path: '',
children: [
{
path: 'orders',
component: MainComponent,
children: [
{
path: '',
component: OrdersComponent,
pathMatch: 'full',
},
{
path: ':orderNumber',
component: OrdersComponent,
},
],
}
],
}];
this.location: Location, this.router: Router - Angular services
Reproduction steps:
- Use this.router.navigateByUrl('/orders'); - we see the OrdersComponent component (to make sure the component is initialized, I added a message in the console to the component's constructor).
- Use this.router.navigateByUrl('/orders/12345'); - we see the same OrdersComponent component (The message appeared in the console again, i.e. the component OrdersComponent has been initialized again).
- Use this.location.replaceState('/orders');
- Use this.router.navigateByUrl('/orders/98765'); - we don't see messages in the console => component constructor not called.
My question is: Why, when repeating steps 3 and 4 (The order numbers can be any), the component is created only for steps 1 and 2 and never again? But if replace this.location.replaceState('/orders'); from Step3 with this.router.navigateByUrl('/orders');, then the constructor will be called on each repetition of steps 3 and 4?
CodePudding user response:
Angular is reusing the component and is only initializing the component when navigating to a route, which you have not been at before. When navigating to a route you have already been at, the component is reused.
If you have to run a specific function either look for another place to put your function call than In the constructor. Maybe take a look at angular lifecycle https://angular.io/guide/lifecycle-hooks
Or maybe make a subscription to ActivatedRoute and run your function every time the Route changes.