shouldDetach method isn't firing when navigatin away from a route in Angular?

57 Views Asked by At

I'm trying to preserve a component (prevent default behavior of destroying it) when user navigates away to a different route, because I want to store all the data inside the forms that it contains. I'm not sure if RouteReuseStrategy can do this, but from what I've heard so far, it can achieve something similar.

Here's how the class looks like (I've copied this solution from stackoverflow):

export class CustomReuseStrategy implements RouteReuseStrategy {
  storedRouteHandles = new Map<string, DetachedRouteHandle>();

 
  shouldDetach(route: ActivatedRouteSnapshot): boolean {
    console.log('should detach fired');
    return route.data.reuseRoute === true;
  }


  store(route: ActivatedRouteSnapshot, handle: DetachedRouteHandle): void {
    this.storedRouteHandles.set(route.routeConfig.path, handle);
  }


  shouldAttach(route: ActivatedRouteSnapshot): boolean {
    return this.storedRouteHandles.has(route.routeConfig.path);
  }


  retrieve(route: ActivatedRouteSnapshot): DetachedRouteHandle {
    return this.storedRouteHandles.get(route.routeConfig.path);
  }


  shouldReuseRoute(future: ActivatedRouteSnapshot, curr: ActivatedRouteSnapshot): boolean {
    return future.routeConfig === curr.routeConfig;
  }
}

But the problem is, that shouldDetach method isn't firing and nothing is logged when I navigate away from the component. Here's how the routing looks like:

{
    path: 'ui/consult',
    component: ConsultComponent,
    providers: [{ provide: RouteReuseStrategy, useClass: CustomReuseStrategy }],
    data: {
      reuseRoute: true,
    },
  }

What can be causing this issue and can it be fixed? Also, is routeReuseStrategy a right solution for what I want, or am I simply misguided here?

0

There are 0 best solutions below