2017-07-14 44 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)); 
    } 

} 
相关问题