Angular Custom Route Reuse Strategy calling ngOnDestroy on stored components?

476 Views Asked by At

I am implementing a custom route reuse strategy for Angular and have a question regarding the calling of the ngOnInit and ngOnDestroy functions. 99% of the questions are related to calling those 2 functions on reused components. However, mine is the exact opposite. My components are stored, but they are still destroyed... So here is the custom route reuse strategy:

  shouldDetach(route: ActivatedRouteSnapshot): boolean {
    return route.data.reuseRoute;
  }

  store(route: ActivatedRouteSnapshot, handle: DetachedRouteHandle): void {
    this._storedRoutes[route.routeConfig.component?.name] = handle;
        console.log("STORED ROUTES", this._storedRoutes);
  }

  shouldAttach(route: ActivatedRouteSnapshot): boolean {
    return route.data?.reuseRoute && !!this._storedRoutes[route.routeConfig.component?.name];
  }

  retrieve(route: ActivatedRouteSnapshot): DetachedRouteHandle {
    if (!route.routeConfig) {
      return null;
    }

    return this._storedRoutes[route.routeConfig.component?.name];
  }

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

And this seems to be working for some routes, but if I visit some child routes and come back to the first one, it is still destroyed. The thing is, the route reuse strategy seems to be working fine.

So this is the console.log:

APP ROUTE REUSE STRATEGY: (shouldAttach) true

app-route-reuse-strategy.ts:25 APP ROUTE REUSE STRATEGY: (shouldAttach) {componentRef: ComponentRef, route: TreeNode, contexts: Map(0)}

app-route-reuse-strategy.ts:35 APP ROUTE REUSE STRATEGY: (retrieve) ComponentA {componentRef: ComponentRef, route: TreeNode, contexts: Map(0)}

app-route-reuse-strategy.ts:13 APP ROUTE REUSE STRATEGY: (store) comB/:id

app-route-reuse-strategy.ts:20 STORED ROUTES {ComponentB: {…}, ComponentA: null, ComponentC: {…}, ComponentD: {…}}

componenta.component.ts:334 ComponentA: OnDestroy

componenta.component.ts:123 ComponentA: OnInit

So I see the order the functions are called in, it checks, if it should attach component A, then retrieves it, then stores the current component, but then for some reason ComponentA, so the one, that has just been attached (or restored), is calling ngOnDestroy before calling ngOnInit again. So basically it is just destroying the older version and recreating it again. I thought, it should just take the component from the store and present it to the user without calling the lifecycle functions. An by the look of it, the constructor is called again as well. Am I missing something?

0

There are 0 best solutions below