【问题标题】:Get all storage keys in ionic storage获取离子存储中的所有存储密钥
【发布时间】:2017-12-13 11:40:45
【问题描述】:

我是 Ionic 应用程序开发的新手,我一直在学习相同的教程。

我一直在尝试使用IonicStorageModule,但即使在 chrome 浏览器移动视图模式下运行应用程序时没有错误,也不会生成本地存储密钥。

在我的app.module.ts,我有

import { IonicStorageModule } from '@ionic/storage';

然后我在imports数组中有以下导入,

  imports: [
    BrowserModule,
    HttpModule,
    IonicModule.forRoot(MyApp),
    IonicStorageModule.forRoot()
  ],

现在,我创建了一个服务,命名为user-settings.service.ts

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

@Injectable()
export class UserSettings {
    constructor(private storage:Storage){}

    favoriteTeam(team,tournamentId, tournamentName) {
        let item = { team: team,tournamentId : tournamentId, tournamentName : tournamentName};
        this.storage.set(team.id , JSON.stringify(item));
    }

    unFavoriteTeam(team) {
        this.storage.remove(team.id);
    }

    getAllFavorites() {
        let items = [];
        return this.storage.forEach((v,k,i) => {
            items.push(JSON.parse(v));
        }).then(() => {
            return items;
        });

    }
}

现在在我的组件类中,我正在尝试检索所有收藏夹,但它没有按预期工作:

  ionViewDidEnter() {
    this.userSettings.getAllFavorites().then((val) => {
      _.forEach(val,(v,k)=> {
        this.favorites.push(v);
      });
    });

    console.log(this.favorites);
  }

我做错了吗?

如何从离子存储中检索所有键值?

这是正确的做法吗?对我来说似乎有很多迭代。

【问题讨论】:

    标签: android angular ionic-framework ionic3


    【解决方案1】:

    我知道这是一个迟到的回复。我发布这个是因为这对其他人有帮助。

    如果您将收藏的项目存储为单独的键;您可以使用forEach 读取所有键和值。

    getAllFavorites() {
        var promise = new Promise((resolve, reject) => {
          this.storage.forEach((value, key, index) => {
            this.list.push(value);
          }).then((d) => {
            resolve(this.list);
          });
        });
        return promise;
    }
    

    注意:在此示例中,我只是在存储完成读取过程后返回值。

    所以,你可以如下使用这个方法;

    this.userSettings.getAllFavorites().then((d) => {
          console.log(d);
    });
    

    正如我在您的代码中看到的,您应该返回一个 promise 而不仅仅是一个列表。

    【讨论】:

    • storage.forEach 只返回第一项,而我的 IndexedDB 存储下有 3 项...对于 Ionic 中的许多错误,切换到 React Native
    【解决方案2】:

    您可以一次存储所有喜欢的球队,例如:

    this.storage.set('favorites', teams)
    

    因此,在ionViewDidEnter,您需要从存储中加载所有收藏夹(作为列表):

    ionViewDidEnter() {
      this.storage.get('favorites', ...).then(val => {
         this.favorites = ...
      }
    }
    

    然后您只需从列表中添加或删除项目并保存。

    【讨论】:

    • 我已经将所有最喜欢的团队详细信息存储在 favoriteTeam 方法中,并在 unFavoriteTeam 方法中删除了相应的详细信息。为什么我不能使用 .forEach 循环它们?为什么我需要在存储中重新设置一些收藏夹数组?
    猜你喜欢
    • 2013-08-11
    • 2012-01-15
    • 1970-01-01
    • 2022-07-23
    • 2018-02-27
    • 1970-01-01
    • 2016-06-28
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多