离子存储提供不确定的价值

时间:2016-12-23 10:56:33

标签: angular storage ionic2

如何在我的应用程序中使用Ionic Storage。我尝试了以下内容,但是当我尝试读出时,我总是将[object Object]作为值返回。当我在一个类中使用get / set方法时,它可以正常工作,但我希望构建我的项目并将存储部分外包。

@Component({
      selector: 'page-login',
      templateUrl: 'login.html'
    })
    export class LoginPage {

      constructor(public testData: TestData) {}

      onLogin(form) { 

        if (form.valid) {
          this.testData.setTestParam("abc");
          console.log("Stored: " +   this.testData.getTestParam()) ;
          // delivers => Stored: [object Object]
        }
    }    

TestData类

@Injectable()
export class TestData {

 constructor(public storage : Storage) {}

 setTestParam(testparam) 
 {
   this.storage.set('test_param', testparam);
 }

 getTestParam(){
   return this.storage.get('test_param').then((value) => {
      return value;
   });
 }
}

3 个答案:

答案 0 :(得分:2)

您的getTestParam()会返回承诺而不是值。 您可以通过执行

来读取值
this.testData.getTestParam().then(data=>{
  console.log(data);
})

答案 1 :(得分:1)

你可以用这个希望它会帮助你。

@Component({
      selector: 'page-login',
      templateUrl: 'login.html'
    })
    export class LoginPage {

      constructor(public testData: TestData) {}

      onLogin(form) { 
        if (form.valid) {
          this.testData.setTestParam("abc");
          this.testData.getTestParam().then((value: any) => {
           console.log(value);
           });
           }}}

TestData Class

@Injectable()
export class TestData {

 constructor(public storage : Storage) {}

 setTestParam(testparam) 
 {
   this.storage.set('test_param', testparam);
 }

 getTestParam(){
        return new Promise((resolve, reject) => {
            this.storage.get('test_param').then((value) => {
                resolve(value);
            });
        });
 }
}

答案 2 :(得分:0)

getTestParam返回Promise而不是正常值。要从Promise读取返回值,您应该使用then方法并使用catch方法来处理任何错误。