获取用户输入值将其存储到localstorage

时间:2017-02-20 05:45:34

标签: angular ionic2

我正在尝试获取用户输入值,将其存储为对象,并在以后需要时使用

 import { Component } from '@angular/core';    
 import { Storage } from '@ionic/storage';

 @Component({
     selector: 'page-login',
     templateUrl: 'login.html'
 })
 export class LoginPage {
     file;
     user = {
         Name: '',
         email: '',
         phone: '',
         Country: ''        
     };
     constructor(public storage: Storage) { }

     writeFile(){    
         var obj = this.user;
         this.storage.set(obj).then(() => {
             this.storage.get(obj).then(() => {
                 console.log(obj.user);
             });
         });
     }
 }

我的HTML是

<ion-content  padding>
    <form  #form="ngForm" (ngSubmit)="logForm(form)" novalidate>
        <ion-list inset  position="bottom">
            <ion-item>
                <ion-label>Name</ion-label>
                <ion-input [(ngModel)]="user.Name" name="Name" required type="text"></ion-input>
            </ion-item>

            <ion-item>
                <ion-label >Email</ion-label>
                <ion-input [(ngModel)]="user.email" name="email" required type="Email"></ion-input>
            </ion-item>
             <ion-item>
                <ion-label >Phone Number</ion-label>
                <ion-input [(ngModel)]="user.phone" name="phone" required type="number"></ion-input>
            </ion-item>
             <ion-item>
                <ion-label >Country</ion-label>
                <ion-input [(ngModel)]="user.Country" name="Country" required type="string"></ion-input>
            </ion-item>
        </ion-list>   
            <button ion-button block (click)="writeFile()">write file</button>   
    </form> 
</ion-content>

因此,当用户输入值时,它将被传递给listing.ts文件中的“user”。我需要将它存储到本地存储。我需要它在我的控制台中看到该对象。

修改 我试过,我得到了错误: enter image description here

1 个答案:

答案 0 :(得分:1)

我认为,当你做this.storage.set(obj);时,这是一个承诺。当您尝试在this.storage.get(obj).then(() => { console.log(obj.user); })查看时,它尚未解决。

让你的代码像这样:

writeFile(){    
    var obj = this.user;
    this.storage.set(key,value).then(() => {
        this.storage.get(obj).then(() => {
            console.log(obj.user);
        });
    });
}

这应该有效。如果有效,请告诉我。 :)

编辑:此外,您必须将其设置为键值格式,如this所示。

我还有一种不同的机制来进行本地存储。 就像这样:

localStorage.setItem('user',JSON.stringify(jsonObject));
var temp = JSON.parse(localStorage.getItem('user'));
console.log("Temp - ",temp);

这也可以。