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

Angular 2-从localStorage存储和获取对象数组,angular,angular-local-storage,Angular,Angular Local Storage,我想在localStorage中存储一个对象数组 这是我在组件阶段存储对象数组的代码片段 this.\u authenticationService.getProfilByLogin(this.form.value.j\u用户名) .订阅(结果=>{ log('insidegetprofils'); log(result.json().ecomServices); setItem('services_assigned',result.json().ecomServices); },错误=>{

我想在localStorage中存储一个对象数组

这是我在组件阶段存储对象数组的代码片段

this.\u authenticationService.getProfilByLogin(this.form.value.j\u用户名)
.订阅(结果=>{
log('insidegetprofils');
log(result.json().ecomServices);
setItem('services_assigned',result.json().ecomServices);
},错误=>{
这是试图将其返回到另一个组件中的代码

从'@angular/core'导入{Component,OnInit};
从“../../model/EcomService”导入{EcomService}”;
@组成部分({
选择器:“应用程序侧栏导航”,
templateUrl:'./sidebar nav.component.html',
样式URL:['./侧栏nav.component.css']
})
导出类SidebarNavComponent实现OnInit{
公共ecomServices:EcomService[]=[];
构造函数(){
}
恩戈尼尼特(){
this.ecomServices=localStorage.getItem('services_assigned');
}
}
这是我的模型

<代码>导出类EcomService{ 公共代码:数字; 公共标签:字符串; }
在本地存储中存储类似的内容时

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

回来的时候做些这样的事情


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

Prathesh的答案的问题是,如果键“services_assigned”在localStorage中不存在,您将得到一个错误

因此,获取阵列的最佳方法是:

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

请注意,如果getItem返回null,因为我们从未将服务存储在那里,那么它将提供一个默认值(空数组)

要存储阵列,请执行以下操作:


localStorage.setItem('services_assigned',JSON.stringify(this.ecomServices));
在我的项目中,我只需创建存储服务来使用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();
    }
}

问题是什么?我的代码无法在localStorage中保存对象的数组并从另一个组件中取回。