离子存储提供未定义的价值

Ionic Storage delivers undefined value

如何在我的应用程序中使用 Ionic Storage。我尝试了以下内容,但是当我尝试读出时,我总是得到 [object Object] 作为值。当我在一个 class 中使用 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]
        }
    }    

测试数据Class

@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;
   });
 }
}

您的 getTestParam() returns 是承诺,而不是价值。 您可以通过

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

getTestParam return 一个 Promise 而不是一个正常值。为了从 Promise 中读取 return 值,您应该使用 then 方法并使用 catch 方法来处理任何错误。

你可以用这个希望对你有帮助。

@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);
           });
           }}}

测试数据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);
            });
        });
 }
}