Angular 子模块的自定义 RouteReuseStrategy [英] Custom RouteReuseStrategy for Angular's child module

查看:21
本文介绍了Angular 子模块的自定义 RouteReuseStrategy的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I want to use this custom route reuse strategy for just one module:

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():

So I've passed into @NgModule() in one of my modules named ChildModule:

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

不幸的是,当我通过它时,它只是被忽略了.尽管添加到我的根目录 AppModule 时工作正常...我不确定这是否重要,但是 ChildModule 被延迟加载.如何解决?

Unfortunately, when I pass it there it simply gets ignored. Although works fine when added to my root AppModule... I'm not sure if it matters, but ChildModule is lazily loaded. How to solve it?

推荐答案

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

I finally achieved it by passing a bit modified CustomRouteStrategy to 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;
    }
}

并在延迟加载的ChildModule的路由中加入data:{reuse:true}:

And adding data: { reuse: true } to the routing of lazily loaded ChildModule:

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

演示更高级的解决方案

这篇关于Angular 子模块的自定义 RouteReuseStrategy的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆