2016-09-07 26 views
1

我想設置我的對象本地和我console.log localstorage,但我越來越undefined。localStorage.setItem(key,val)顯示undefiend

這裏是我的功能

  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陣列globaly聲明。

在我的console.log(項目)我能夠看到我的對象。

我想用本地存儲將該對象推到我的空數組,以便我可以使用ngFor在UI中顯示。

我的console.log(this.quciOrder);顯示undefiend。

+0

如果'quickOrder'是全局聲明的 - 就像你說的那樣 - 'this'的用法是什麼?也許你應該在問題中包含更多的代碼。 – cartant

+0

,因爲它是在類上聲明的,所以爲了使用函數內的數組我們應該使用這個關鍵詞來訪問它 –

回答

0

您是否在使用LocalStorageIonic?如果不是,我認爲如果你使用它會更好,因爲它讓事情變得更容易(請注意,LocalStorage存儲引擎使用瀏覽器的本地存儲系統來存儲鍵/值對,所以它在哪裏是相同的數據被存儲)。就像你可以在LocalStorage docs看到你可以初始化它像這樣

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)set(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); 

    }); 
} 
0

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