1

I am new to angular. I've read about new features in Angular 5 - Using 'onSameUrlNavigation' now it’s possible to reload a page when the router receives a request to navigate to the same UR ? Currently i am using version 4.4.6. 'onSameUrlNavigation' not available in angular version 4.

Is there any other way to do the same thing in angular 4. What are the things that i have to do to accomplish this requirement.

providers: [
  RouterModule.forRoot(routes, {
     onSameUrlNavigation: 'reload'
  })
]
Janak
  • 4,986
  • 4
  • 27
  • 45
Ishara Madawa
  • 1,502
  • 2
  • 14
  • 27

3 Answers3

4

I did it with this :

this.router.routeReuseStrategy.shouldReuseRoute = function(){
  return false;
};

this.router is the instance of your angular Router class.

Aakash Uniyal
  • 1,519
  • 4
  • 17
  • 32
2

You can use RouteReuseStrategy. In the component where you want to reload on route reuse you can do this:

this.router.routeReuseStrategy.shouldReuseRoute = (
 future: ActivatedRouteSnapshot,
 curr: ActivatedRouteSnapshot
) => {
 if (future.url.toString() === curr.url.toString()) {
  // reload the page
 }
};
Efe
  • 5,180
  • 2
  • 21
  • 33
2

It can be done in a much simpler way. Below is a small sample code:

in routing.module: "/product/: id / details"

import { ActivatedRoute, Params, Router } from ‘@angular/router’;

export class ProductDetailsComponent implements OnInit {

constructor(private route: ActivatedRoute, private router: Router) {
    this.route.params.subscribe(params => {
        this.paramsChange(params.id);
    });

}

// Call this method on page load
ngOnInit() {
}

// Call this method on change of the param
paramsChange(id) {
}

The general explanation is ... why to destroy already existed component instance and create a new one for the same case when it causes performance degradation?

It is the exactly the same behavior as using routes pattern /product/:id where the same component instance is also kept for /product/5, /product/6, ...

So you should re-init the component on the base of some emitted event (resolver/guard) and not on the base of OnInit hook because of the same component instance.

ikos23
  • 4,879
  • 10
  • 41
  • 60