2017-07-14 13 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関数を呼び出す前localstorage.getItem機能を使用してのlocalStorageで値の

+2

の可能性のある重複した[HTML5のlocalStorage:項目が設定されているかどうかを確認](https://stackoverflow.com/questions/3262605/html5-localstorage-check-if-item-is-set)を使用している – anoop

答えて

1

チェックをお知らせください。

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

両方の行に、typoを設定しますか? –

+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)); 
    } 

} 
関連する問題