我正在使用 localstorage 在其中存储数据并在构造函数中从中进行检索,我希望检查变量保留在刷新页面时的值比较其值为0,在获得更新值后,如果check == 0
则应该进入功能。
我坚持认为这是可能的吗?
check=0;
ngOnInit() {
if(this.check==0)
{
this.list =new Array();
this.list.push("Purchase a ring for my beautiful wife","get new GALAXY Note 150","Complete kevin's work ASAP","Buy 2 dozen eggs","Get milk on my way to home");
localStorage.setItem('list', JSON.stringify(this.list));
this.check++;
localStorage.setItem('incre', JSON.stringify(this.check));
}
this.check=JSON.parse( localStorage.getItem('incre'));
this.list=JSON.parse( localStorage.getItem('list'));
}
答案 0 :(得分:2)
constructor
删除所有内容。 public check: number = 0;
ngOnInit() {
this.check = JSON.parse(localStorage.getItem('incre')) || 0;
if (this.check === 0) {
// do the rest
}
}
答案 1 :(得分:1)
如果我正确理解了您的问题,那么this.check=JSON.parse( localStorage.getItem('incre'));
应位于构造函数的顶部,然后您应该在if
试试这个
check=0;
list = any[];
constructor() {
this.check=JSON.parse( localStorage.getItem('incre'));
if(this.check == undefined || this.check==0)
{
this.list =new Array();
this.list.push("Purchase a ring for my beautiful wife","get new GALAXY Note 150","Complete kevin's work ASAP","Buy 2 dozen eggs","Get milk on my way to home");
localStorage.setItem('list', JSON.stringify(this.list));
this.check++;
localStorage.setItem('incre', JSON.stringify(this.check));
}
this.list=JSON.parse( localStorage.getItem('list'));
}
答案 2 :(得分:0)
将此语句移至构造函数的开头
constructor() {
this.check=JSON.parse(localStorage.getItem('incre'));
if(this.check==0)

答案 3 :(得分:0)
你甚至没有像dr.nio的代码那样设置initital 0
。
public check: number = 0;
ngOnInit() {
this.check = JSON.parse(localStorage.getItem('incre'))
if (!this.check) {}
}
清晰可读。