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

泄露秘密 提交于 2019-11-26 18:15:57

问题


I have an application, with views behind routes, I need to be able to continue from the point when the route changed, but after going back, the component is in its initial state.

Is there any way how to keep the state of a component?


回答1:


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.




回答2:


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.



来源:https://stackoverflow.com/questions/33940095/angular2-routing-keeping-state-of-component-when-route-changes

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