Angular2 doesn't work Custom Reuse Strategy with Lazy module loading

前端 未结 5 1151
花落未央
花落未央 2020-12-08 16:52

I tried to use custom reuse strategy in my angular2 project, but I found it doesn\'t work with lazy module loading. Anyone who know about this? My project i

5条回答
  •  温柔的废话
    2020-12-08 17:27

    Use this one. It use component name as the key to store and retrieve the Handles.

    import {ActivatedRouteSnapshot, DetachedRouteHandle, RouteReuseStrategy} from '@angular/router';
    
    export class CustomReuseStrategy implements RouteReuseStrategy {
    
    
      handlers: { [key: string]: DetachedRouteHandle } = {};
    
    
      shouldDetach(route: ActivatedRouteSnapshot): boolean {
        return true;
      }
    
      store(route: ActivatedRouteSnapshot, handle: DetachedRouteHandle): void {
        this.handlers[this.getKey(route)] = handle;
      }
    
      shouldAttach(route: ActivatedRouteSnapshot): boolean {
        return !!route.routeConfig && !!this.handlers[this.getKey(route)];
      }
    
      retrieve(route: ActivatedRouteSnapshot): DetachedRouteHandle {
        if (!route.routeConfig) {
          return null;
        }
        return this.handlers[this.getKey(route)];
      }
    
      shouldReuseRoute(future: ActivatedRouteSnapshot, curr: ActivatedRouteSnapshot): boolean {
        return curr.routeConfig === future.routeConfig;
      }
    
      private getKey(route: ActivatedRouteSnapshot) {
        let key: string;
        if (route.component) {
          key = route.component['name'];
        } else {
          key = route.firstChild.component['name'];
        }
        return key;
      }
    
    }
    

提交回复
热议问题