如何在本地存储 angular 中存储数组?

How to store array in local storage angular?

我试图将数据存储在一个数组中,以便稍后在其他组件中获取它,但它引发了错误:

ERROR TypeError: Cannot read property 'push' of undefined

我使用了本地存储。

onSubmit() {
    let email = this.AuthForm.get("email").value;
    let password = this.AuthForm.get("password").value;
    let nomcomplet = "";
    let occupation = "";
    let niveau = 0;
    let newUser = new User(email, password, nomcomplet, occupation, niveau);
    console.log(newUser);
    let val: any = [];
    val = this.storage.get(this.key);
    val.push(newUser.email);
    this.storage.set(this.key, JSON.stringify(val));
}

我希望在本地存储中找到所有存储的值,但实际是错误的,之前只存储了最后一个值

屏幕截图

enter image description here

您已将数据存储为字符串,因此当您检索它时,您应该将其解析回对象。

设置存储空间

this.storage.set(this.key, JSON.stringify(val));

从存储中检索

const storageVal = this.storage.get(this.key)
const val = JSON.parse(storageVal)

您可能还想添加一种方法来处理存储对象不存在的情况(returns null 值)

const storageVal = this.storage.get(this.key)
const val = storageVal ? JSON.parse(storageVal) : []

好的,让我们试试这个

     let email = this.AuthForm.get("email").value;
     let password = this.AuthForm.get("password").value;
     let nomcomplet = "";
     let occupation = "";
     let niveau = 0;
     let newUser = new User(email, password, nomcomplet, occupation, niveau);
     console.log(newUser);
     let array: any = [];

     if (localStorage.getItem(keyToFindOrSave)) {
      //exist data on storage
      //so grab the storage
       array = JSON.parse(localStorage.getItem(this.key)); //we overwrite the same arry with the data from LocalStorage

    }

      console.log(array); //Watching if have some old data!
      array.push(newUser) //So we push the newUser , if exist something on localStorage the if before actually have the data
      console.log(array); //Watching with new data and old data
      localStorage.set(keyToFindOrSave, JSON.stringify(array)); //and save the data

记住 keyToFindOrSave 必须始终相同 (y)

当您需要另一个组件上的数据时,只需使用

let dataFromStorage : any;
if (localStorage.getItem(keyToFindOrSave)) { //always ask if exist the localStorage =D
 dataFromStorage = JSON.parse(localStorage.getgetItem(keyToFindOrSave));
}

Some Screenshot LocalStorage Data