CustomReuseStrategy不适用于延迟加载的组件

时间:2017-10-25 18:26:29

标签: angular angular-routing

我有一个组件,它是一个现在正在延迟加载的模块的一部分。问题是每次使用路由时组件都会重新初始化。

这是我的路线。

{
    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
    }
},

以下是加载模块的路径。

{
    path: '',
    component: ActivityEngineComponent,
    data: {
        shouldDetach: true, // Route will be resused. See CustomReuseStrategy.
        title: null
    }
},

我正在app模块和延迟加载的模块中导入以下类,并将它们作为提供程序应用:

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 }
]

这是我的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;
    }

}

是否有人使用CustomReuseStrategy加载了延迟加载的组件?

1 个答案:

答案 0 :(得分:1)

你不需要shouldDetach: true懒惰加载孩子,只有在你定义了组件的地方才需要它。