从长远来看,我正在使用 Ionic Storage 来存储数据。现在我想在进入统计页面时检索数据,所以我调用了我创建的服务并在统计页面的 ngOnInit 中编写了方法,但是如果我正确理解了这个问题,它就无法识别存储类的实例化但奇怪的是,当我在 ionViewWillEnter() 中编写方法时它确实有效。我使 ngOnInit 和 ionViewWillEnter 都异步,但我仍然收到 ngOnInit 错误。如果我没记错的话,我可以使用 ionViewWillEnter 技巧,它类似于在我的用例中调用 ngOnInit 中的方法,但我仍然很好奇它为什么会出错......
统计页面的TS:
import { StatsService } from './../service/stats.service';
import { Component, OnInit } from '@angular/core';
@Component({
selector: 'app-statistics',
templateUrl: './statistics.page.html',
styleUrls: ['./statistics.page.scss'],
})
export class StatisticsPage implements OnInit {
testsAmount: any = 0;
constructor(public statsService: StatsService) {}
addJohn(){
this.statsService.set("1", "john");
}
removeAll(){
this.statsService.clearAll();
}
async getJohn(){
console.log(await this.statsService.get("1"));
}
async ngOnInit() {
await this.statsService.set("testSetngOnInit", "blabla");
console.log("testSet initialized from the ngOnInit");
console.log(await this.statsService.get("testSetngOnInit"));
}
async ionViewWillEnter(){
await this.statsService.set("testSetionViewWillEnter", "blabla");
console.log("testSet initialized from the ionViewWillEnter");
console.log(await this.statsService.get("testSetionViewWillEnter"));
}
}
服务 TS :
import { Injectable } from '@angular/core';
import { Storage } from '@ionic/storage-angular';
import * as CordovaSQLiteDriver from 'localforage-cordovasqlitedriver';
@Injectable({
providedIn: 'root'
})
export class StatsService {
// private _storage: Storage | null = null;
private _storage: Storage;
constructor(public storage: Storage) {
this.init();
}
async init() {
// If using, define drivers here: await this.storage.defineDriver(/*...*/);
await this.storage.defineDriver(CordovaSQLiteDriver);
const storage = await this.storage.create();
this._storage = storage;
}
async keyExistence(key: string){
if(await this.get(key) == null){
return false;
}
else{
return true;
}
}
// Create and expose methods that users of this service can
// call, for example:
async set(key: string, value: any) {
await this._storage?.set(key, value);
}
async clearAll() {
await this._storage.clear();
}
async get(key: string) {
return await this._storage.get(key);
}
}
我的 IndexDB :
提前致谢 !