angular - Angular 子模块的自定义 RouteReuseStrategy

标签 angular angular-routing angular-module angular-router

我只想对一个模块使用这个自定义路由重用策略:

export class CustomRouteReuseStrategy extends RouteReuseStrategy {
    public shouldDetach(route: ActivatedRouteSnapshot): boolean { return false; }
    public store(route: ActivatedRouteSnapshot, detachedTree: DetachedRouteHandle): void {}
    public shouldAttach(route: ActivatedRouteSnapshot): boolean { return false; }
    public retrieve(route: ActivatedRouteSnapshot): DetachedRouteHandle { return null; }
    public shouldReuseRoute(future: ActivatedRouteSnapshot, curr: ActivatedRouteSnapshot): boolean {
        return true;
    }
}

所以我在名为 ChildModule 的模块之一中传递了 @NgModule():

providers: [
        {
            provide: RouteReuseStrategy,
            useClass: CustomRouteReuseStrategy
        }
]

不幸的是,当我将它传递到那里时,它只是被忽略了。虽然添加到我的根 AppModule 时工作正常...我不确定它是否重要,但是 ChildModule 是延迟加载的。如何解决?

最佳答案

我最终通过将稍微修改过的 CustomRouteStrategy 传递给 AppModule 来实现它:

export class CustomRouteReuseStrategy extends RouteReuseStrategy {
    public shouldDetach(route: ActivatedRouteSnapshot): boolean { return false; }
    public store(route: ActivatedRouteSnapshot, detachedTree: DetachedRouteHandle): void {}
    public shouldAttach(route: ActivatedRouteSnapshot): boolean { return false; }
    public retrieve(route: ActivatedRouteSnapshot): DetachedRouteHandle { return null; }
    public shouldReuseRoute(future: ActivatedRouteSnapshot, curr: ActivatedRouteSnapshot): boolean {
        return (future.routeConfig === curr.routeConfig) || future.data.reuse;
    }
}

并添加 data: { reuse: true } 到延迟加载的 ChildModule 的路由:

{
    path: 'some-path',
    data: { reuse: true },
    loadChildren: './child.module#ChildModule',
},

Demo with more advanced solution

关于angular - Angular 子模块的自定义 RouteReuseStrategy,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44875644/

相关文章:

angular - 如何在 Angular 5 中获取当前路线

angularjs - 在有 Angular UI路由器中处理尾部斜杠

angularjs - $routeProvider 不适用于 html5Mode

angular - 路由和模块

angular - Angular 7 中检测到循环依赖

javascript - 如何在 Angular 8 的路由上加载模块?

javascript - angular 2.0 相当于 $scope.$apply

javascript - 将 Angular 应用程序作为 Express Server 中的静态内容提供服务

angular - 如何在浏览器中显示 Angular9 变化检测过程?

javascript - Angular 2检查下一条路线OnDestroy