0

So I made a simple todo list with Ionic and Angular. You can add and delete things to a list, which should be visible all the time. Everything works this far except for saving the data when closing the app.

Here is my home.page.ts:

export class HomePage {
  name = '';
  namelist = Array<string>();
  
  constructor(public storage: Storage) {
    let json = JSON.stringify(this.namelist);
    localStorage.setItem('namelist', json);
    var test = localStorage.getItem('namelist');
    this.namelist = JSON.parse(test);
  }

  add() {
    if (this.name.length > 0) {
      let name = this.name;
      this.namelist.push(name);
      this.name = '';
    }
  }

  delete(index) {
    this.namelist.splice(index, 1);
  }
2
  • 1
    You should use "Storage" from ionic, since this storage is permanent. LocalStroage is not permanent. Here is some documentation: ionicframework.com/docs/angular/storage Sep 27, 2020 at 14:11
  • I think your namelist is empty when u save it into the localstroage in the constructor, u can set a breakpoint to check
    – tsu
    Sep 27, 2020 at 14:23

1 Answer 1

0

try this

export class HomePage {
  name = '';
  namelist = Array<string>();
  
  constructor(public storage: Storage) {
    this.getDataLocalStorage()
  }

  add() {
    if (this.name.length > 0) {
      let name = this.name;
      this.namelist.push(name);
      this.name = '';
    }
  }

  delete(index) {
    this.namelist.splice(index, 1);
  }

  updateLocalStorage(){
    localStorage.setItem('namelist', JSON.stringify(this.namelist));
  }

  getDataLocalStorage(){

    try {
      const test = localStorage.getItem('namelist');
      this.namelist = JSON.parse(test);
    } catch (error) {
      console.log(error)
    }
   
  }
}
0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.