Angular2 Routing - keeping state of component when route changes [duplicate]

痴心易碎 提交于 2019-11-27 13:12:56

update 2

That's now fixed (Angular 2.3) for the new router by https://github.com/angular/angular/pull/13124 which allows to provide a custom reuse strategy.

For an example see also https://www.softwarearchitekt.at/post/2016/12/02/sticky-routes-in-angular-2-3-with-routereusestrategy.aspx

Angular docs https://angular.io/api/router/RouteReuseStrategy

update 2 This answer is only for a long ago discontinued router version.

See https://angular.io/docs/ts/latest/guide/router.html#!#guards for how to do it in the current router.

original

If your components implements CanReuse and returns true from

routerCanReuse(next: ComponentInstruction, prev: ComponentInstruction) {
  return true;
}

then the component is kept and reused instead of destroyed and recreated.

Another way is to keep the data in a shared service and fetch them from there when the component is recreated.

There is an open issue on this exact scenario in https://github.com/angular/angular/issues/5275

You can use routerCanReuse only if the new component and the old component(when you hit the 'back' button) are of the same Component type.

As Günter suggested your only option right now if the Components are of different type is to keep state in a shared service.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!