从Ionic2存储中获取多个键值

cap*_*com 5 ionic-framework ionic2 angular

使用Ionic2存储,我在自定义提供程序中完成了以下操作,我可以确认键值对已设置,我可以单独检索它们:

this.storage.set('one', 1);
this.storage.set('two', 2);
this.storage.set('three', 3);
Run Code Online (Sandbox Code Playgroud)

问题是我的一个页面中有一个函数需要访问HTTP请求的所有这三个值,所以我可以得到其中一个像这样:

this.storage.get('one').then((value) => {
    // Preform http request sending value in POST data
});
Run Code Online (Sandbox Code Playgroud)

但是如何一次获得多个键值?我是否需要嵌套这些调用,或者是否有一种更简单的方法可以在一次调用中访问多个键,这样我就可以执行以下操作:

this.storage.get(['one', 'two', 'three']).then((values) => {
    console.log(values.one); // I dunno, something like this
});
Run Code Online (Sandbox Code Playgroud)

Vic*_*nyi 11

我为此目的使用了Promise.all

Promise.all([this.storage.get("email"), this.storage.get("username")]).then(values => {

      console.log("email", values[0]);
      console.log("username", values[1]);

      // every other thing can happen here e.g call a method

});
Run Code Online (Sandbox Code Playgroud)

  • 我也使用它,它比其他列出的方法更受欢迎. (2认同)

Sam*_*ath 5

您可以简单地按如下所示进行。

this.storage.forEach( (value, key, index) => {
    console.log("value", value);//store these values as you wish
    console.log("key", key);
    console.log("Index" index);
})
Run Code Online (Sandbox Code Playgroud)

来自 Api 文档。

 /**
   * Iterate through each key,value pair.
   * @param iteratorCallback a callback of the form (value, key, iterationNumber)
   * @return Promise that resolves when the iteration has finished.
   */

  forEach(iteratorCallback: (value: any, key: string, iterationNumber: Number) => any): Promise<null> {
    return this._dbPromise.then(db => db.iterate(iteratorCallback));
  }
Run Code Online (Sandbox Code Playgroud)