代码之家  ›  专栏  ›  技术社区  ›  Ron

父路由OnInit在导航到第一个子级时触发

  •  2
  • Ron  · 技术社区  · 7 年前

    我有一个问题,当我将路由更改为子路由时,父路由 OnInit 触发器。如果我有3个子级,父级最多初始化3次(当我第一次导航到子级时,每个子级最多初始化3次)。

    我知道这是因为我 CustomReuseStrategy 但是我不知道为什么以及如何修复它(我从其他地方复制了CustomReuseStragy)

    A sandbox of the above problem

    1 回复  |  直到 7 年前
        1
  •  1
  •   Ron    7 年前

    我能够使用不同的定制重用策略来解决这个问题

    import { ActivatedRouteSnapshot, DetachedRouteHandle, RouteReuseStrategy } from '@angular/router';
    
    
    export class CustomReuseStrategy implements RouteReuseStrategy {
      public static handlers: { [key: string]: DetachedRouteHandle } = {};
    
      public shouldDetach(route: ActivatedRouteSnapshot): boolean {
        return true;
      }
    
      public store(route: ActivatedRouteSnapshot, handle: DetachedRouteHandle): void {
        CustomReuseStrategy.handlers[this.getRouteUrl(route)] = handle;
      }
    
      public shouldAttach(route: ActivatedRouteSnapshot): boolean {
        return !!CustomReuseStrategy.handlers[this.getRouteUrl(route)];
      }
    
      public retrieve(route: ActivatedRouteSnapshot): DetachedRouteHandle {
        if (!route.routeConfig) {
          return null;
        }
    
        return CustomReuseStrategy.handlers[this.getRouteUrl(route)];
      }
    
      public shouldReuseRoute(future: ActivatedRouteSnapshot, curr: ActivatedRouteSnapshot): boolean {
        return future.routeConfig === curr.routeConfig && JSON.stringify(future.params) === JSON.stringify(curr.params);
      }
    
      private getRouteUrl(route: ActivatedRouteSnapshot) {
        return route['_routerState'].url.replace(/\//g, '_');
      }
    }
    
    推荐文章