2017-07-14 80 views
0

我想設置一個鍵值,但我只想做它,如果它不存在。如何查找密鑰是否已存在於本地存儲中?

在我的component1.ts文件中,我在構造函數中設置了鍵和值,但是我想添加一個檢查條件,只有當鍵之前沒有創建時,該命令才應該執行。如果密鑰已經存在,請不要執行。

下面是我的代碼:

import { Component } from '@angular/core'; 
import { NavController } from 'ionic-angular'; 

@Component({ 
    selector: 'page-home', 
    templateUrl: 'home.html' 
}) 
export class HomePage { 
myname=''; 
list: Array<string> = ['a','b','c']; 
sectionObj = {}; 
getresume = {}; 
stored_name = ''; 

    constructor(public navCtrl: NavController) { 
    this.sectionObj = { "name" : this.myname, 
         "contactno" : "0", 
         "email" : "[email protected]" 
        }; 
// below line should only execute if "resume" key does not exist 
    localStorage.setItem("resume",JSON.stringify(this.sectionObj)); 
    } 

} 

請致電localstorage.setItem功能之前,建議

+2

的可能的複製[HTML5的localStorage:檢查項目被設定](https://stackoverflow.com/questions/3262605/html5-localstorage-check-if-item-is-set)您使用 – anoop

回答

1

檢查使用localstorage.getItem功能的localStorage值。

if(localStorage.getItem("resume") === null) { 
    localStorage.setItem("resume",JSON.stringify(this.sectionObj)); 
} 
+0

在兩行中設置,錯字? –

+0

@JessicaStorm,這確實是一個錯字。現在更正。感謝您的發現。 – nipuna777

1

檢查密鑰的值。這裏是你可以嘗試的代碼。

import { Component } from '@angular/core'; 
import { NavController } from 'ionic-angular'; 

@Component({ 
    selector: 'page-home', 
    templateUrl: 'home.html' 
}) 
export class HomePage { 
myname=''; 
list: Array<string> = ['a','b','c']; 
sectionObj = {}; 
getresume = {}; 
stored_name = ''; 

    constructor(public navCtrl: NavController) { 
    this.sectionObj = { "name" : this.myname, 
         "contactno" : "0", 
         "email" : "[email protected]" 
        }; 
    // below line should only execute if "resume" key does not exist 
    if(localStorage.getItem('resume') === null) 
     localStorage.setItem("resume",JSON.stringify(this.sectionObj)); 
    } 

} 
相關問題