【问题标题】:Angular 2/4 : how to change route without recreating the componentAngular 2/4:如何在不重新创建组件的情况下更改路线
【发布时间】:2018-01-14 20:04:03
【问题描述】:

我有几个路由到同一个组件(即 /projects、/projects/create、/projects/:id 和 children,都指向我的 ProjectComponent)。 在 /projects/:id 之间导航时,只有 :id 更改一切都很好,我可以订阅参数并相应地更新我的内容,但是当我从 /projects 导航到 /projects/create 或 /projects/:id 时,组件被重新创建。

有没有办法导航到指向同一组件的路由而不重新创建它?

【问题讨论】:

标签: javascript angular ngroute


【解决方案1】:

你应该实现一个自定义的RouteReuseStrategy

创建一个实现RouteReuseStrategy的服务:

export class CustomReuseStrategy implements RouteReuseStrategy {

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

    shouldDetach(route: ActivatedRouteSnapshot): boolean {
        return true;
    }

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

并将此提供程序添加到@NgModule

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

您可以将CustomReuseStrategy 调整为仅具有可以重用组件的某些路径,但我会留给您自己了解如何操作。

source

【讨论】:

  • 感谢它是完美的,我实际上遇到了这篇文章,但我忽略了它,因为整个附加/分离/存储/检索的东西不是我想要的。我需要多加注意。
猜你喜欢
  • 2017-09-27
  • 2019-10-14
  • 2019-06-21
  • 1970-01-01
  • 2018-02-13
  • 1970-01-01
  • 2014-01-25
  • 1970-01-01
  • 2016-05-13
相关资源
最近更新 更多