-1

I want to set a key value but I only want to do it if it does not exists already.

In my component1.ts file, I am setting the key and the value in the constructor but I want to add a check that this command should only execute if the key is not created before. If the key is already present there, don't execute.

Below is my code:

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

}

Please advise

nipuna-g
  • 6,252
  • 3
  • 31
  • 48
  • 2
    Possible duplicate of [HTML5 localStorage: check if item is set](https://stackoverflow.com/questions/3262605/html5-localstorage-check-if-item-is-set) – anoop Jul 14 '17 at 11:09

2 Answers2

0

Check for the value in localstorage using localstorage.getItem function before calling the localstorage.setItem function.

if(localStorage.getItem("resume") === null) {
    localStorage.setItem("resume",JSON.stringify(this.sectionObj));
}
nipuna-g
  • 6,252
  • 3
  • 31
  • 48
0

Check the value of the key. Here is the code you may try.

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

}
nipuna-g
  • 6,252
  • 3
  • 31
  • 48