Ionic 2本地存储获取并显示数据



嗨,我无法访问本地存储中的数据,它总是给我错误. 我需要帮助在家中显示我的数据。 感谢您的帮助:)

错误:

打字稿错误 类型为"Promise"的参数不可分配给类型为"字符串"的参数。

this.user = JSON.parse(this.storage.get(this.key((; prompt.present((;

打字稿

import { Component } from '@angular/core';
import { IonicPage, NavController, NavParams, ViewController, AlertController } from 'ionic-angular';
import {Storage} from '@ionic/storage';
/**
* Generated class for the CrudPage page.
*
* See http://ionicframework.com/docs/components/#navigation for more info
* on Ionic pages and navigation.
*/
@IonicPage()
@Component({
selector: 'page-crud',
templateUrl: 'crud.html',
})
export class CrudPage {
user: any = [] ;
key: any;
constructor(public navCtrl: NavController,
public navParams: NavParams,
public viewCtrl: ViewController,
public alertCtrl: AlertController,
public storage: Storage) {
this.storage.forEach( (value) => {
this.user.push(value);
});
}
ionViewDidLoad() {
console.log('ionViewDidLoad CrudPage');
}
add() {
let prompt = this.alertCtrl.create({
title: 'Add User',
message: "Enter information of the user",
inputs: [
{
name: 'name',
placeholder: 'name'
},
{
name: 'password',
placeholder: 'password'
},
],
buttons: [
{
text: 'Cancel',
handler: data => {
console.log('Cancel clicked!');
}
},
{
text: 'Save',
handler: data => {
let key = data.name + data.password;
this.storage.set(key, JSON.stringify(data));
console.log(data);
}
}
]
});
this.user = JSON.parse(this.storage.get(this.key));
prompt.present();
}
delete(key){
this.storage.remove(key);
}
update(key){
}
}

.HTML

<!--
Generated template for the CrudPage page.
See http://ionicframework.com/docs/components/#navigation for more info on
Ionic pages and navigation.
-->
<ion-header>
<ion-navbar>
<ion-title>Crud</ion-title>
</ion-navbar>
</ion-header>

<ion-content padding>
<button ion-button clear icon-start color="dark" (click)="add()">
<ion-icon name="add-circle">Add User</ion-icon>
</button>
<br>
<ion-grid text-center>
<ion-row>
<ion-col width-100>
USERS
</ion-col>
</ion-row>
<ion-row>
<ion-col width-33>
<strong>User Name</strong>
</ion-col>
<ion-col width-33>
<strong>Password</strong>
</ion-col>
<ion-col width-33>
<strong>Action</strong>
</ion-col>
</ion-row>
<ion-row *ngFor="let users of user" text-center>
<ion-col width-33>
<p>{{users.name}}</p>
</ion-col>
<ion-col width-33>
<p>{{users.password}}</p>
</ion-col>
<ion-col width-33>
<button ion-button clear icon-start color="dark" (click)="delete(users.name+users.password)">
<ion-icon name="trash"></ion-icon>
</button>
<button ion-button clear icon-start color="dark" (click)="update(users.name+users.password)">
<ion-icon name="create"></ion-icon>
</button>
</ion-col>
</ion-row>
</ion-grid>
</ion-content>

请帮忙:)非常感谢:)

this.storage.get(this.key(返回一个承诺,你必须这样做:

this.storage.get(this.key).then(value => {
this.user = JSON.parse(value);
});

https://ionicframework.com/docs/storage/

最新更新