Search code examples
angularangular-routingsubscribengoninitroute-parameters

Route parameters - subscribe method


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


Solution

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