我想设置一个键值,但如果它不存在,我只想这样做。
在我的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" : "a@a.com"
};
// below line should only execute if "resume" key does not exist
localStorage.setItem("resume",JSON.stringify(this.sectionObj));
}
}
请告知
答案 0 :(得分:1)
在调用localstorage.getItem
函数之前,使用localstorage.setItem
函数检查localstorage中的值。
if(localStorage.getItem("resume") === null) {
localStorage.setItem("resume",JSON.stringify(this.sectionObj));
}
答案 1 :(得分: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" : "a@a.com"
};
// below line should only execute if "resume" key does not exist
if(localStorage.getItem('resume') === null)
localStorage.setItem("resume",JSON.stringify(this.sectionObj));
}
}