我有一个 Ionic 2 应用程序,它以列表的形式显示包内的用户项目。我创建了一个函数来检索包内的当前项目索引,它在用户启动应用程序时被触发。它检查 Ionic Storage(内部)内存中的索引名称-值对是否为空。在这种情况下,索引设置为 0 并存储在内部和工作内存中。否则,从内部存储器中检索索引并用于设置工作存储器。
但是,self.storage.set(myString, '0');
在下面的代码中会抛出错误TypeError: Cannot call method 'set' of undefined
。我检查了 usingconsole.dir
并且确实self.storage
在then(...);
块内未定义。为什么会这样,我该如何解决?
导入、声明、构造函数
import { Injectable } from '@angular/core';
import { Storage } from '@ionic/storage';
declare var self: ItemStorageService;
@Injectable()
export class ItemStorageService {
workingMemoryItems: Array<any>;
workingMemoryIndex: number;
packageIndex: number;
constructor(public storage: Storage) {
self = this;
self.packageIndex = 0;
self.initializeIndex().then(
res => {
console.log(res);
},
err => {
console.log(err);
}
)
}
// Other methods including initializeIndex()
}
初始化索引函数
public initializeIndex(): Promise<any> {
console.dir(self.storage); // Returns Storage object
var myString = 'index_item_package_' + self.packageIndex;
return new Promise((resolve, reject) => {
self.storage.get(myString).then(
val => {
if ((val === null) || (val === 'null')) {
console.dir(self.storage); // Returns undefined
self.storage.set(myString, '0');
self.workingMemoryIndex = 0;
resolve('Working memory index not found and set to 0');
} else {
self.workingMemoryIndex = val as number;
resolve('Working memory index found and set to ' + val);
}
},
err => {
self.storage.set(myString, 0);
self.workingMemoryIndex = 0;
reject('Working memory index not found and set to 0');
}
)
});
}