Angular 2 - 从localStorage存储和获取对象数组

时间:2017-07-20 10:16:38

标签: angular angular-local-storage

我想在 localStorage 中存储一系列对象。

这是我的代码片段,用于存储组件阶段的对象数组。

this._authenticationService.getProfilByLogin(this.form.value.j_username)
  .subscribe(result => {
     console.log('inside getting profils');
     console.log(result.json().ecomServices);
     localStorage.setItem('services_assigned', result.json().ecomServices);
  }, error => {

这是试图将其恢复到另一个组件中的代码。

import {Component, OnInit} from '@angular/core';
  import {EcomService} from "../../model/EcomService";

  @Component({
    selector: 'app-sidebar-nav',
    templateUrl: './sidebar-nav.component.html',
    styleUrls: ['./sidebar-nav.component.css']
  })
  export class SidebarNavComponent implements OnInit {


    public ecomServices: EcomService[] = [];

    constructor() {
    }

    ngOnInit() {
      this.ecomServices = localStorage.getItem('services_assigned');
    }
  }

这是我的模型

export class EcomService {

  public eseCode: number;
  public eseLabel: string;

}

3 个答案:

答案 0 :(得分:6)

在本地存储存储中存储类似的东西

localStorage.setItem('services_assigned', JSON.stringify(this.ecomServices));

虽然回来做这样的事情。

this.ecomServices = JSON.parse(localStorage.getItem('services_assigned'));

答案 1 :(得分:0)

Prathmesh答案的问题在于,如果本地存储中不存在键“ services_assigned”,则会出现错误。

所以获取数组的最好方法是:

this.ecomServices = JSON.parse(localStorage.getItem('services_assigned') || '[]');

请注意,如果getItem返回null,这将如何提供默认值(空数组),因为我们从未在此存储服务。

要存储数组:

localStorage.setItem('services_assigned', JSON.stringify(this.ecomServices));

答案 2 :(得分:0)

在我的项目中,我只是简单地创建了与localStorage一起使用的存储服务:

@Injectable()
export class CacheService {

    constructor() {}

    public get(key) {
        const data = localStorage.getItem(key);
        return !_.isEmpty(data) ? _.cloneDeep(JSON.parse(data)) : [];
    }

    public set(data, key) {
        localStorage.setItem(key, JSON.stringify(data));
    }

    public reset() {
        localStorage.clear();
    }
}
相关问题