Angular2 不适用于延迟模块加载的自定义重用策略

标签 angular routes lazy-loading reusability

我尝试使用 custom reuse strategy在我的 angular2 项目中, 但我发现它不适用于惰性模块加载。 有谁知道这件事吗?我的项目是 angular 2.6.4

重用策略.ts

import {RouteReuseStrategy, ActivatedRouteSnapshot, DetachedRouteHandle} from "@angular/router";

export class CustomReuseStrategy implements RouteReuseStrategy {

    handlers: {[key: string]: DetachedRouteHandle} = {};

    shouldDetach(route: ActivatedRouteSnapshot): boolean {
        console.debug('CustomReuseStrategy:shouldDetach', route);
        return true;
    }

    store(route: ActivatedRouteSnapshot, handle: DetachedRouteHandle): void {
        console.debug('CustomReuseStrategy:store', route, handle);
        this.handlers[route.routeConfig.path] = handle;
    }

    shouldAttach(route: ActivatedRouteSnapshot): boolean {
        console.debug('CustomReuseStrategy:shouldAttach', route);
        return !!route.routeConfig && !!this.handlers[route.routeConfig.path];
    }

    retrieve(route: ActivatedRouteSnapshot): DetachedRouteHandle {
        console.debug('CustomReuseStrategy:retrieve', route);
        if (!route.routeConfig) return null;
        return this.handlers[route.routeConfig.path];
    }

    shouldReuseRoute(future: ActivatedRouteSnapshot, curr: ActivatedRouteSnapshot): boolean {
        console.debug('CustomReuseStrategy:shouldReuseRoute', future, curr);
        return future.routeConfig === curr.routeConfig;
    }

}

应用程序模块.ts

const appRoutes: Routes = [
  { path: 'crisis-center', component: CrisisListComponent },
  { path: 'heroes', loadChildren: 'app/hero-list.module#HeroListModule' },
  { path: '',   redirectTo: '/crisis-center', pathMatch: 'full' }
];
@NgModule({
  imports: [ ... ],
  declarations: [ ... ],
  providers:[
    {provide: RouteReuseStrategy, useClass: CustomReuseStrategy}
  ],
  bootstrap: [ AppComponent ]
})
export class AppModule { }

我把<input>到这两个组件,我测试了它。

CrisisListComponent中输入的值已存储,但是 HeroListComponent lazy-loaded 的值没有保留。

我不知道它还不被支持。 谢谢你帮助我。

最佳答案

RouteReuseStrategy 确实适用于 LazyLoaded 组件。

这里的问题是您使用 route.routeConfig.path 作为存储和检索句柄的键。

我不知道为什么,但是对于 LazyLoaded 模块,route.routeConfig.path 在执行 shouldAttach 时是空的

我使用的解决方案是在我的路由中定义一个自定义键,例如:

{ path: '...', loadChildren: '...module#...Module', data: { key: 'custom_key' } }

可以在 ActivatedRouteSnapshot 中轻松访问此键值,例如:

route.data.key

使用此 key ,您可以正确存储和检索句柄。

关于Angular2 不适用于延迟模块加载的自定义重用策略,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42383546/

相关文章:

angular - 如何取消选择 md-select Angular2 中的选定选项

ruby-on-rails - 将静态页面部署到域根并将rails应用程序部署到子域

android - 在 Android 中将图像与一段文本内联

ajax - 如何在过滤primefaces中的惰性数据表后更新其他组件

php - Laravel 5.1 路由未定义重定向

angular - 我们如何在 ionic3 的不同延迟加载页面中导入管道文件?

html - 过渡在页面加载时无法正确显示

css - 如何让行内 div 内的按钮进行换行? ( flex 和 Angular )

angular - 在 Angular 中使用带有 RxJS 的声明式/响应式(Reactive)数据访问方法时如何获取 "pass"数据?

重定向到 Razor 页面中带有 ID 的页面