我有使用路由的导航。每次当我转到其他页面并返回时,我都会丢失所有变量值。我怎样才能解决这个问题?
Posted
技术标签:
【中文标题】我有使用路由的导航。每次当我转到其他页面并返回时,我都会丢失所有变量值。我怎样才能解决这个问题?【英文标题】:i have navigation using routing. every time when i go to other page and come back i lose all values of variables . how can i fix this? 【发布时间】:2021-12-30 03:07:06 【问题描述】:例如: 我有组件用户和数组“userInfo”。我在“userInfo”中推送了一些信息。然后当我转到另一个组件(使用 routerLink)然后返回到用户组件时,“userInfo”数组为空。
这里:每次我导航到另一个页面时,返回的 cartItems 数组都会变为空
export class CartComponent implements OnInit
cartItems:Item[] = [];
quantity:number = 1;
constructor(private cartDataService:CartDataService)
up()
this.quantity++;
down()
if(this.quantity>1)
this.quantity--;
ngOnInit(): void
this.cartDataService.myCartData$
.subscribe(
cartData =>
this.cartItems.push(cartData)
)
【问题讨论】:
我试过了。订阅 cartData 作为数组,然后 concat 但我得到了相同的结果 【参考方案1】:您必须使用状态管理工具来帮助您在应用程序中保存全局数据。
我个人推荐 NgRx [1]
[1]https://ngrx.io/docs
【讨论】:
我建议从小处着手,使用共享服务(可能在 root 中提供),而不是跳入复杂的状态管理解决方案,例如 ngrx :)。 @OctavianMărculescu 这是肯定的 ?以上是关于我有使用路由的导航。每次当我转到其他页面并返回时,我都会丢失所有变量值。我怎样才能解决这个问题?的主要内容,如果未能解决你的问题,请参考以下文章