无法在angular 6的组件init上的sessionStorage中保存数组

时间:2018-10-09 07:20:21

标签: angular angular6

我正在获取组件中的数据,并希望通过服务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;
  }
}

2 个答案:

答案 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;
 }
}

希望有帮助!