I have a component that is part of a module that is now being lazy loaded. The problem is that the component is re-initializing every time the route is used.
Here is my route.
{
path: 'activities',
loadChildren: () => System.import('../containers/activity-engine/activity-engine.module').then((file: any) => {
return file.default;
}),
data: {
shouldDetach: true, // Route will be resused. See CustomReuseStrategy.
title: null
}
},
Here is the route for the module being loaded.
{
path: '',
component: ActivityEngineComponent,
data: {
shouldDetach: true, // Route will be resused. See CustomReuseStrategy.
title: null
}
},
I am importing the following classes in app module and the lazy loaded module, and they are being applied as providers:
import { RouteReuseStrategy } from '@angular/router';
import { Location, LocationStrategy, PathLocationStrategy } from '@angular/common';
import { CustomReuseStrategy } from '../../shared/router/custom-reuse-strategy';
providers: [
{ provide: RouteReuseStrategy, useClass: CustomReuseStrategy },
{ provide: LocationStrategy, useClass: PathLocationStrategy }
]
Here is my CustomReuseStrategy:
export class CustomReuseStrategy implements RouteReuseStrategy {
handlers: { [key: string]: DetachedRouteHandle } = {};
// Determines if this route (and its subtree) should be detached to be reused later.
shouldDetach(route: ActivatedRouteSnapshot): boolean {
// We can choose which routes should be resued (i.e. shouldDetach === true)
// (https://stackoverflow.com/questions/41483187/conditionally-apply-router-reuse-strategy-for-angular2-routes).
return !!route.data && !!(route.data as any).shouldDetach;
}
store(route: ActivatedRouteSnapshot, handle: DetachedRouteHandle): void {
this.handlers[route.routeConfig.path] = handle;
}
shouldAttach(route: ActivatedRouteSnapshot): boolean {
return !!route.routeConfig && !!this.handlers[route.routeConfig.path];
}
retrieve(route: ActivatedRouteSnapshot): DetachedRouteHandle {
if (!route.routeConfig) return null;
return this.handlers[route.routeConfig.path];
}
shouldReuseRoute(future: ActivatedRouteSnapshot, curr: ActivatedRouteSnapshot): boolean {
return future.routeConfig === curr.routeConfig;
}
}
Is there a was to use CustomReuseStrategy
with lazy loaded components?