Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular - Navigate to current same URL with component reload not the whole page

Tags:

angular

routes

I am using Angular 5 library, I want to navigate to the current URL with reload (refresh) the whole component, not the page, I have read about navigation to current URL in Angular document.

And that it is what I need:

 /**
 * Define what the router should do if it receives a navigation request to the current URL.
 * By default, the router will ignore this navigation. However, this prevents features such
 * as a "refresh" button. Use this option to configure the behavior when navigating to the
 * current URL. Default is 'ignore'.
 */
onSameUrlNavigation: 'reload' | 'ignore';

Now, I have tried to set the onSameUrlNavigation property to reload and then navigate to the same URL, but nothing happend, like this:

this.router.onSameUrlNavigation = 'reload';
this.router.navigate(['view'], { queryParams: { QueryUUID: selectedId } });

Anyone who has used this before can help?

like image 851
Ebraheem Alrabeea Avatar asked Feb 06 '18 00:02

Ebraheem Alrabeea


2 Answers

I have found this workaround method since the onSameUrlNavigation property in Angular 5.1 is not what I need.

I just need to override shouldReuseRoute, so added an exception for the component route that I want to refresh, if the current and future route are equal view.

And also I can navigate to other routes without problems, even for navigate from Angular Material sidenav.

this.router.routeReuseStrategy.shouldReuseRoute = function (future: ActivatedRouteSnapshot, curr: ActivatedRouteSnapshot) {
  if (future.url.toString() === 'view' && curr.url.toString() === future.url.toString()) {
    return false;
  }
  return (future.routeConfig === curr.routeConfig);
};

Update:

For those they want to use the new onSameUrlNavigation property in Angular 5.1 you can refer to this blog:

https://medium.com/engineering-on-the-incline/reloading-current-route-on-click-angular-5-1a1bfc740ab2

like image 164
Ebraheem Alrabeea Avatar answered Sep 18 '22 13:09

Ebraheem Alrabeea


If I understand you correctly, this is how I do it:

ngOnInit(): void {
    this.route.params.subscribe(
        params => {
            const id = +params['id'];
            this.getMovie(id);
        }
    );
}

Or to watch query parameters:

ngOnInit(): void {
    this.route.queryParams.subscribe(param => {
        this.pageTitle = 'Movie List';
        this.getMovies();
    });
}

In the ngOnInit, I watch for changes to the parameters. When the parameters change, I re-retrieve the data.

Since the data is all bound, the page "refreshes" with the newly retrieved data.

like image 32
DeborahK Avatar answered Sep 21 '22 13:09

DeborahK