-1

"Angular does not create the component if it is already present in the DOM. It reuses the component instance. This implies that the ngOnInit life cycle hook is not invoked when the user navigates to the component again."

Based on this, I cannot understand why ngOnInit lifecyle method is invoked again if it contains the .subscribe method when we retrieve the route parameters.

Could anyone help me with this?

Thank you.

Chaka15
  • 1,105
  • 1
  • 8
  • 24
Katherine
  • 11
  • 5

1 Answers1

0

We can access route parameters in couple of ways, by using -->

this.route.snapshot.params["someParam"]

or

this.route.params.subscribe()

Let's say we use second approach with .subscribe, since you are interested in that case. Even though it is inside ngOnInit lifecycle method it will get triggered if route parameters have been changed. We are subscribed to certain changes (route params changes), so if they change we get the latest values.

All things concluded, it's not about ngOnInit. It's about our subscription. We are "listening" to those changes.

FYI, if you use first approach this.route.snapshot.params["someParam"] where we don't have .subscribe this one won't fire again. It will be run only once and not again since we are "not interested" to potential upcoming changes of route parameters.

Chaka15
  • 1,105
  • 1
  • 8
  • 24
  • So, could we subscribe to these changes by using .subscribe to another method (and not in ngOnInit)? Or it works just in this way? Thank you. – Katherine Jan 16 '22 at 12:29
  • It has the most meaning to `subscribe` in `ngOnInit` since it's the first method that is called in lifecycle of the component. Method `ngOnChanges` is only called before `ngOnInit` if there is `@Input` property in component, but `ngOnInit` makes more sense. – Chaka15 Jan 16 '22 at 12:34