10

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?

Ebraheem Alrabeea
  • 2,130
  • 3
  • 23
  • 42

5 Answers5

11

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.

DeborahK
  • 57,520
  • 12
  • 104
  • 129
  • Thank you for your response, I have tried the same idea but with no success, because all service and charts I need to change its initial data already have been created, By creating a method that call the code inside `ngOnInit` but not worked, I need to reload the page with the new parameters. – Ebraheem Alrabeea Feb 06 '18 at 14:37
  • As far as I know ... the above technique is how its normally done. There are no other features I know of to "reload" the page. Maybe if you could provide a plunkr or stackblitz demonstrating the issue, we could provide more assistance. – DeborahK Feb 06 '18 at 17:46
  • I am reading this blog, https://medium.com/engineering-on-the-incline/reloading-current-route-on-click-angular-5-1a1bfc740ab2, it is have what I want but still there is minor problem. – Ebraheem Alrabeea Feb 06 '18 at 17:51
  • You may get a more valid answer then posting a question to his blog. Since this is a (very little publicized) new feature, there are probably not many of us here familiar with it. – DeborahK Feb 06 '18 at 17:57
  • Yeah, it is still new feature and not worked perfectly with me, Anyway, your answer is useful in some cases, and I have figured out a solution for now, Thank you for your help. – Ebraheem Alrabeea Feb 06 '18 at 19:59
  • This is the right answer. Don't waste your time on onSameUrlNavigation – spankymac May 22 '18 at 23:46
6

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


Update:

It is better to create a custom RouteReuseStrategy that override the default behavior, here it is how I do that:

export class AppRouteReuseStrategy implements BaseRouteReuseStrategy {

  // all other methods will be the same as the default

  /*
  * Determines if a route should be reused.
  * This strategy returns `true` when the future route config and current route config are identical.
  * 
  * but we want to refresh the route if the data.refreshComponent is true in the route definition
  * */
  shouldReuseRoute(future: ActivatedRouteSnapshot, curr: ActivatedRouteSnapshot): boolean {
    // so we need to check if it is true. if not, we return the default behavior
    return future.data.refreshComponent ? false : future.routeConfig === curr.routeConfig;
  }
}

Then will add this as a provider in the AppModule:

{ provide: RouteReuseStrategy, useClass: AppRouteReuseStrategy }

And the last thing to do is to mark which component you want to refresh in case of navigate to the same route, like this:

const routes: Routes = [
  {
    path: 'view',
    component: ViewComponent,
    data: { refreshComponent: true },
  }
]
Ebraheem Alrabeea
  • 2,130
  • 3
  • 23
  • 42
  • To the best of my understanding per https://github.com/angular/angular/issues/21115 the router is a singleton so you're setting this setting application-wide even if it's just set in one component – fIwJlxSzApHEZIl Feb 04 '22 at 16:28
  • Yes, you have to put it in a shared place, but remember I just override the setting in one case when the route is `view` else the base behavior will be processed. – Ebraheem Alrabeea Feb 07 '22 at 15:51
1

In route module: add below in each route declaration

runGuardsAndResolvers: 'always'

and

@ngModule({
 imports: [RouterModule.forRoot(routes, {onSameUrlNavigation: ‘reload’})],
 exports: [RouterModule],
 })

for e.g category/:id

and this below part will be under Component

ngOnInit() {
    this.activeRoute.queryParams.subscribe(queryParams => {
        // do something with the query params
    });
        this.activeRoute.params.subscribe(routeParams => {
        this.loadUserDetail(routeParams.id);
    });
}

for each route change say for e.g category/11 and category/12 it will call loadUserDetail function everytime.

So without refreshing page you will fetch data from server and update dom for same route with different roureParams.

Swapnil Dalvi
  • 999
  • 9
  • 23
0

In terms of rel-loading the entire page, the normal <a href="/">Reload Page</a> tag works just fine for me. I tried using the "onSameUrlNavigation" function, but it was not reloading the entire page the way I want.

desoga
  • 4,179
  • 1
  • 15
  • 18
0

You can use the angular router events for this purpose.

import { takeUntil, filter } from "rxjs/operators";
import { Router, NavigationEnd } from "@angular/router";

this.router.events.pipe(
      filter((event): event is NavigationEnd => event instanceof NavigationEnd),
      takeUntil(this._unsubscribeAll),
).subscribe(() => {
      this.cache = {};
      this.cachedRows = [];
      this.getRollingJobs(this.page);
});
casper123
  • 1,736
  • 4
  • 21
  • 39