我在localStorage中保存了多个密钥和值,如下所示:
Day1 1
Day2 2
Day3 3
我想检索所有的键和值,并将它们显示在列表视图中。
我的主页.html如下所示:
<ion-item-divider >
<ion-label >{{key}} </ion-label>
<ion-label color="secondary">{{value}}</ion-label>
</ion-item-divider>
我的主页如下:
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];
}
}
角度文档:https://angular.io/api/common/KeyValuePipe#description
我可以使用follow查询来解决这个问题。
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>