【发布时间】:2020-06-20 14:07:35
【问题描述】:
我是 Angular 新手,正在寻找一种在页面刷新时维护共享数据的解决方案。
我有 2 个组件,即冷却器和配方。冷却器组件将选定的冷却器信息共享给配方组件。我在这里使用共享服务在 2 个组件之间传递数据。在配方组件出现导航数据后。页面刷新后,数据丢失。如何在页面刷新时/之后维护数据。
组件1(冷却器):
createQuotation(){
this.selectedCoolers = [];
for(let i=0; i< this.coolers.length; i++)
{
if(this.coolers[i].check)
{
this.selectedCoolers.push(this.coolers[i]);
}
}
this.coolerservice.updateSelectedCoolers(this.selectedCoolers);
}
共享服务(CoolerService)
updateSelectedCoolers(coolers : Cooler[]){
console.log("From updateSelectedCoolers");
console.log(coolers);
this._selectedCoolersSource.next(coolers);
}
成分2(配方):
selectedCoolers : Cooler[];
constructor(private router: ActivatedRoute, private http: HttpClient, private coolerservice: CoolerService){}
ngOnInit() {
this.coolerservice.selectedCoolers$.subscribe(
coolers => {
console.log("In ngOnInit");
console.log(coolers);
this.selectedCoolers = coolers;
console.log(this.selectedCoolers); //Line1
}
);
console.log("After Navigation");
console.log(this.selectedCoolers); //Line2
}
selectedCoolers 有超过 50 个。 我想在页面刷新后将数据保留在 this.selectedCoolers 中。 还有'console.log(this.selectedCoolers); //Line2' 显示未定义。
【问题讨论】:
-
您可以在获取数据后立即将数据保存在会话存储或本地存储中。
-
selectedCoolers 的数量已超过 50 个。将所有这些数据存储在本地/会话存储中是否是一种好方法?感谢您的快速回复。 :)
-
本地存储最多可以存储 10MB 的数据,50 个数据点非常小,我认为这不是问题。
-
将数据存储在会话存储中并且可以正常工作。但是这里的Service有什么用呢? sessionStorage.setItem 可以从 Component1 和 sessionStorage.getItem 从 Component2 完成。
-
在下面添加了我的答案。
标签: angular typescript