android - 获取 ionic 存储中的所有存储 key

标签 android angular ionic-framework ionic3

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

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

在我的 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);
  }

我做错了什么吗?

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

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

最佳答案

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

如果您将喜欢的项目存储为单独的键;您可以使用 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 而不仅仅是一个列表。

关于android - 获取 ionic 存储中的所有存储 key ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47792139/

相关文章:

android - 从 Google Maven 手动下载 JAR

angular - ngx-bootstrap 模态在测试期间不会隐藏

android - 编译 android 源代码时 linux-x86/bin/acp 的权限被拒绝

android 服务器消息未显示在聊天屏幕上

java - 如何更改 java 文件中的 XML 按钮属性?

css - CSS 中的 Angular Material 2 目标元素

html - 如果数据库未返回 Angular 5 移动应用程序中特定标签的任何值,如何在 html 中隐藏标签?

mobile-website - 移动浏览器上的 ionic 侧边菜单无法正常工作

android - ionic native 相机拍照但不显示。我想拍照并在同一页面上显示

android - 无法使用 ionic 平台添加 android 安装最新的 android 版本