Search code examples
angularangular-router

Angular 2+ ngOnInit() not being called if router navigates to current route( with new query params) from itself


In my home.component.ts, my ngOnInit method is:

ngOnInit() {
    console.log("ngoninitcalled");
    this.activatedRoute.queryParams.subscribe((params:Params) => {
        let refresh = params['refresh'];
        if(refresh){
            // do something refreshing
        }
    }
}

And here is my customFunction

customFunction(email: string, username:string) {
    // do something custom
    this.router.navigate([''],{queryParams: {refresh:true}});     
}

The '' route redirects to home.component.ts or HomeComponent(snippet of whose are above).

On checking console logs, I see that when HomeComponent is called with refresh param from other components(via this.router.navigate([''], {queryParams: {refresh:true}}), ngOnInit() is called. But if its called from HomeComponent itself(as in above code), ngOnInit() is not called.

So is it the expected behavior and can I safely call this.ngOnInit() after the router.navigate in my custom function to invoke ngOnInit() manually(assuming ngOnInit will never be called if HomeComponent is redirected to from itself)?


Solution

  • It is expected behavior that the ngOnInit is not called when navigating to the same component with different parameters.

    But you should not call ngOnInit manually.

    The subscription will get notified each time the parameters change. So code within the subscribe method will execute each time. You don't need to call ngOnInit.

    Try it by moving your console.log within the subscribe.