循环本地存储并显示离子应用程序中所有键和值的完整列表

Loop localstorage and display complete list of all key and value in ionic app

我已经在本地存储中保存了多个键和值,如下所示:

Day1  1
Day2  2
Day3  3

我想检索所有键和值并将它们显示在列表视图中。

我的 home.html 如下所示:

<ion-item-divider >
<ion-label >{{key}} </ion-label>
<ion-label color="secondary">{{value}}</ion-label>    
</ion-item-divider>

我的 home.ts 如下所示:

for (var i = 0, len = localStorage.length; i < len; i++) {
      this.key = localStorage.key(i);
      console.log(this.key);
      this.value = localStorage.getItem(localStorage.key(i));
      console.log(this.value);
    }

我只能显示最后一条记录。请指出我哪里做错了。

您可以在 *ngFor 中使用键值管道。

<ion-item-divider *ngFor="let item of mainObject|keyvalue">
  <ion-label>{{item.key}} </ion-label>
  <ion-label color="secondary">{{item.value}}</ion-label>
</ion-item-divider>

在您的 TS 文件中:

mainObject = {...localStorage};
(or)
mainObject = {};
for (const key in localStorage) {
      if (Object.prototype.hasOwnProperty.call(localStorage, key)) {
          this.mainObject[key] = localStorage[key];
      }
    }

Angular 文档:https://angular.io/api/common/KeyValuePipe#description

我可以使用以下查询解决问题。

home.ts如下:

allObj: any[] = [];
for ( var i = 0, len = localStorage.length; i < len; ++i ) {
      this.result1 = localStorage.key( i );
      this.result2 = localStorage.getItem( localStorage.key( i ) );
      this.result3 = this.result1 + " " + this.result2;
      var y = this.result3;
      console.log(y);
      this.allObj.push(this.result3);
    }

home.html如下:

<ion-item no-lines text-wrap *ngFor="let item of allObj" >
<p>{{item}}</p>
</ion-item>