如何防止角度分量破坏和重新初始化?

时间:2019-07-05 05:52:15

标签: angular angular-routing

我有一个带有开放图层地图组件的角度应用程序。每次重新打开地图组件时,它都应处于相同状态。 App具有路由器出口和角度拆分区域(按拆分区域),每个组件都可以在路由器出口或拆分区域中处于活动状态。可以使用RouteReuseStrategy将组件保留在路由器出口中。但是,如果我导航到路由器出口中的其他路线并打开包含开放图层地图组件的分割区域,我如何获得相同的组件而不是不同的实例?我的html看起来像这样:

    <as-split #homeViewSplit direction="horizontal">
      <as-split-area [order]="(routerOutletOrder | async)">
        <router-outlet></router-outlet>
        <app-toolbar *ngIf="(toolbarVisible | async)"></app-toolbar>
      </as-split-area>
      <as-split-area *ngIf="(mapSplitVisible | async)" [order]="1">
        <app-map2d></app-map2d>
        <app-toolbar></app-toolbar>
      </as-split-area>
      <as-split-area *ngIf="(contentSplitVisible | async)" [order]="2">
        <app-content></app-content>
      </as-split-area>
      <as-split-area *ngIf="(propertiesSplitVisible | async)" [order]="3">
        <app-properties></app-properties>
      </as-split-area>
      <as-split-area *ngIf="(leasSplitVisible | async)" [order]="4">
        <app-contracts></app-contracts>
      </as-split-area>
      <as-split-area *ngIf="(sidePanelsSplitVisible | async)" [order]="5">
        <app-side-panels></app-side-panels>
      </as-split-area>
    </as-split>

所以顺序如下。包含路由器外圈的第一个分割区域总是可见的。

  1. 打开应用-> app-map2组件显示在路由器出口
  2. 导航到“内容”,并且应用程序内容组件显示在路由器出口中
  3. 还使包含app-map2d的第二个拆分区域可见

->现在,app-map2d重新初始化。如何预防呢?正如我所说的,我已经实现了存储DetachedRouteHandle的RouteReuseStrategy:

export class CacheRouteReuseStrategy implements RouteReuseStrategy {
    routesToCache: string[] = ['map'];
    storedRouteHandles = new Map<string, DetachedRouteHandle>();

    // Decides if the route should be stored
    shouldDetach(route: ActivatedRouteSnapshot): boolean {
        if (route.data === undefined) {
            return false;
        }
        return this.routesToCache.indexOf(route.data['key']) > -1;
    }

    //Store the information for the route we're destructing
    store(route: ActivatedRouteSnapshot, handle: DetachedRouteHandle): void {
       this.storedRouteHandles.set(route.data['key'], handle);
    }

    //Return true if we have a stored route object for the next route
    shouldAttach(route: ActivatedRouteSnapshot): boolean {
        if (route.data === undefined) {
            return false;
        }
        return this.storedRouteHandles.has(route.data['key']);
    }

    //If we returned true in shouldAttach(), now return the actual route data for restoration
    retrieve(route: ActivatedRouteSnapshot): DetachedRouteHandle {
        return this.storedRouteHandles.get(route.data['key']) as DetachedRouteHandle;
    }

    //Reuse the route if we're going to and from the same route
    shouldReuseRoute(future: ActivatedRouteSnapshot, curr: ActivatedRouteSnapshot): boolean {
       return future.routeConfig === curr.routeConfig;
    }
}

0 个答案:

没有答案