Search code examples
angularangular-router

How to implement RouteReuseStrategy only when user goes back (history)?


I have an Angular 2 project where I have implemented a custom-reuse-strategy that stores the detached route and reuse them if they already exist.

It's good, but I would like to use this mechanism only if user click on navigator go back button, and not if the user click directly on some links in my page or menu.

The purpose is that if user is coming from go back button, the route will be displayed has he left, but if user click on a link or menu, the page will be reloaded and data from server will be fetched again!

I tried to see if there is the information in the ActivatedRouteSnapshot that the user is coming from history and not directly from a link (with router.navigate) but I can't see nothing.

Is there a way to achieve what I would like?


Solution

  • You can detect the back button is pressed doing:

    constructor(location: LocationStrategy) {
      location.onPopState(() => {
        console.log('Back button pressed!');
        console.log(window.location);
      });
    }
    

    You should add @Injectable() to inject the LocationStrategy.