我是 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/