我正在获取组件中的数据,并希望通过服务sessionStorage
保存在EquipmentStoreService
中,但不会保存在sessionStorage中。我该如何处理这个问题?
export class DashboardComponent implements OnInit {
equipments: Equipment[];
constructor(private equipmentService: EquipmentService,
private equipmentStore: EquipmentStoreService) { }
ngOnInit() {
this.equipmentService.getItems()
.subscribe( data => {
this.equipmentStore.updateThisStore(data);
this.equipments = this.equipmentStore.all();
});
}
}
这是我的商店服务
@Injectable({
providedIn: 'root'
})
export class EquipmentStoreService {
private static STORAGE_KEY = 'current-equipments';
equipments: Array<Equipment>;
constructor () {
this.equipments = JSON.parse(sessionStorage.getItem(EquipmentStoreService.STORAGE_KEY) || '[]');
}
updateStore() {
localStorage.setItem(EquipmentStoreService.STORAGE_KEY, JSON.stringify(this.equipments));
}
updateThisStore(equipments: Equipment[]) {
this.equipments = equipments;
this.updateStore();
}
all() {
return this.equipments;
}
}
答案 0 :(得分:1)
在updateStore函数中,您将数组保存在localStorage
中而不是sessionStorage
中。使用sessionStorage.setItem
功能将项目保存在会话存储中。
答案 1 :(得分:1)
这是因为要在localStorage中设置数据并将其存储在sessionStorage中。
像这样更新您的商店服务:
@Injectable({
providedIn: 'root'
})
export class EquipmentStoreService {
private static STORAGE_KEY = 'current-equipments';
equipments: Array<Equipment>;
constructor () {
this.equipments = JSON.parse(sessionStorage.getItem(EquipmentStoreService.STORAGE_KEY) || '[]');
}
updateStore() {
sessionStorage.setItem(EquipmentStoreService.STORAGE_KEY, JSON.stringify(this.equipments));
}
updateThisStore(equipments: Equipment[]) {
this.equipments = equipments;
this.updateStore();
}
all() {
return this.equipments;
}
}
希望有帮助!