【问题标题】:Ionic Storage delivers undefined value离子存储提供未定义的价值
【发布时间】:2016-12-23 19:43:19
【问题描述】:

如何在我的应用程序中使用 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;
   });
 }
}

【问题讨论】:

  • 如果您使用的是 chrome,请转到您的调试控制台并进入您的应用程序选项卡,然后查看数据是如何保存在 WebSQL 或使用的任何驱动程序下的

标签: angular storage ionic2


【解决方案1】:

您的 getTestParam() 返回一个承诺而不是价值。 您可以通过执行读取值

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

【讨论】:

  • 我必须在我的 LoginPage 类中执行此操作?
  • 是..代替`console.log("Stored:" + this.testData.getTestParam()) ;`
  • 谢谢,工作。这是正确的方法,还是您会推荐其他方法?
  • 这是从承诺中获得价值的方式
  • 替代方案是什么?有更短的方法吗?对我来说看起来很多代码。
【解决方案2】:

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

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

测试数据类

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

【讨论】:

    【解决方案3】:

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

    【讨论】:

      猜你喜欢
      • 2017-06-01
      • 2017-02-07
      • 2018-01-17
      • 2018-03-19
      • 2018-01-26
      • 2018-02-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多