Angular2路由-更改路线时保持组件状态 [英] Angular2 Routing - keeping state of component when route changes

查看:140
本文介绍了Angular2路由-更改路线时保持组件状态的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个应用程序,该应用程序具有在路线后面的视图,我需要能够从路线更改的那一点开始继续,但是回去之后,该组件处于初始状态.

有什么办法可以保持组件的状态?

解决方案

更新2

新路由器已通过 https://github.com修复了该问题(Angular 2.3)/angular/angular/pull/13124 ,它可以提供自定义重用策略.

有关示例,另请参见 https://www.softwarearchitekt.at/post/2016/12/02/sticky-routes-in-angular-2-3-with-routereusestrategy.aspx

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) {
  return true;
}
 

然后将组件保留并重复使用,而不是销毁并重新创建.

另一种方法是将数据保留在共享服务中,并在重新创建组件时从那里获取数据.

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路由-更改路线时保持组件状态的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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