Angular2 Routing - 当路由改变时保持组件的状态 [英] Angular2 Routing - keeping state of component when route changes
问题描述
我有一个应用程序,在路由后面有视图,我需要能够从路由改变时的点继续,但返回后,组件处于初始状态.
有没有办法保持组件的状态?
更新 2
现在通过 https://github.com 为新路由器修复了(Angular 2.3)/angular/angular/pull/13124 允许提供自定义重用策略.
Angular 文档 https://angular.io/api/router/RouteReuseStrategy>
更新 2 此答案仅适用于很久以前停产的路由器版本.
参见 https://angular.io/docs/ts/latest/guide/router.html#!#guards 了解如何在当前路由器中执行此操作.
原创
如果您的组件实现了 CanReuse 并返回true
来自
routerCanReuse(next: ComponentInstruction, prev: ComponentInstruction) {返回真;}
然后组件被保留和重用,而不是被销毁和重新创建.
另一种方法是将数据保存在共享服务中,并在重新创建组件时从那里获取它们.
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?
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.
这篇关于Angular2 Routing - 当路由改变时保持组件的状态的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!