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

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

07-26 03:37