Search code examples
angularngoninit

How to reload a view after router.navigate in Angular 4?


I have a switch to shop function which is controlled by a header component and displays a dashboard for that venue.

In that header component, I navigate to dashboard route, even if I already in that route.

this.router.navigate(['/venues', this.currentVenue._id, 'dashboard']);

But it doesn't trigger ngOnInit hook again so my view is not reloaded.

What is the correct workaround for such case?


Solution

  • Do you need to reload the view? Or just reget some data?

    If you only need to reget data based on the routing parameter, you can do this:

    ngOnInit(): void {
        this.route.params.subscribe(
            params => {
                const id = +params['id'];
                this.getMovie(id);   // <- Or whatever you need to do here
            }
        );
    }
    

    In the ngOnInit, this code subscribes to the route parameters. So every time the parameters change, even if the view is not changed/reloaded, the change will be picked up as part of the subscription and the associated callback is executed.