【发布时间】:2021-05-29 21:27:47
【问题描述】:
从长远来看,我正在使用 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:
提前致谢!
【问题讨论】:
-
并非如此,Angular 不使用与 AgularJS 相同的语法。在您发送的帖子中,他们在整个实例化方面遇到了问题,而在我的情况下,当我尝试在 ngOnInit 中使用它时只有一个错误
-
此错误不是角度错误,也不是打字稿错误,也不是 ionic 框架错误,而是 Javascript 错误。这实际上与错误相同,您正在调用值为 undefined 的变量的方法或属性。
-
我知道问题的性质,但我无法说出原因。马特早些时候建议这可能是一个时间问题,但在那种情况下,我不知道如何告诉 ngOnInit 等待服务实例化,因为据我了解,ngOnInit 不会等待构造函数完成该过程,而是等待由于某种原因,构造函数及时让 ionViewWillEnter 能够使用它......好吧,看起来你可能比我更了解这个问题,你能告诉我我可以在哪里工作来解决我的问题吗? :)
标签: typescript ionic-framework ionic-storage