1

我正在尝试在本地设置我的对象,并且我 console.log 那个 localstorage 但我越来越不确定。

这是我的功能

            searchBar(item) { //item is object here as parameter

             console.log(item);
        localStorage.setItem('object',JSON.stringify(item))
this.quickOrder.push(localStorage.getItem('object'));

    console.log(this.quickOrder);

                  }

我有一个全局声明的 quickOrder 数组。

在我的 console.log(item) 中,我可以看到我的对象。

我正在尝试将该具有本地存储的对象推送到我的空数组,以便我可以利用 ngFor 在 UI 中显示。

我的控制台.log(this.quciOrder); 显示不羁。

4

2 回答 2

0

你在使用LocalStoragefromIonic吗?如果没有,我认为使用它会更好,因为它使事情变得更容易(请注意,LocalStorage 存储引擎使用浏览器的本地存储系统来存储键/值对,所以它在哪里是相同的存储的数据)。就像您在LocalStorage 文档中看到的一样,您可以像这样初始化它

import { Component } from '@angular/core';
import { Storage, LocalStorage } from 'ionic-angular';

@Component({
  template: `<ion-content></ion-content>`
});
export class MyClass{
 constructor(){
   this.local = new Storage(LocalStorage);
 }
}

然后使用get(key)andset(key, value)方法,但请记住,这两种方法都返回一个承诺,所以你应该这样做

searchBar(item) { //item is object here as parameter

  console.log(item);

  this.local.set('object',JSON.stringify(item)).then(() => {

    // Code to execute after the value is set in the LocalStorage...

  });

  // Or

  this.local.get('object').then((data) => {

    // Code to execute after the value is get from the LocalStorage...
    this.quickOrder.push(data);

  });
}
于 2016-09-07T09:41:36.467 回答
0

在推入数组之前,您需要 JSON.parse localStorage 数据。localStorage.setItem('object',JSON.stringify(item)); this.quickOrder.push(JSON.parse(localStorage.getItem('object')));

于 2016-09-07T11:07:22.973 回答