我有一個Ionic 2應用程序,以列表的形式顯示包內的用戶項目。我創建了一個函數來檢索Package中的當前Item索引,它被觸發,用戶啓動應用程序。它檢查Ionic Storage(內部)存儲器中的索引名稱 - 值對是否爲空。在這種情況下,索引設置爲0並存儲在內部和工作存儲器中。否則,從內部存儲器中檢索索引並用於設置工作存儲器。Ionic Storage在承諾中未定義?
但是,在下面的代碼中self.storage.set(myString, '0');
會引發錯誤TypeError: Cannot call method 'set' of undefined
。我使用console.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()
}
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');
}
)
});
}
你在哪裏設置'self'? – Saravana
我聲明它低於我的導入,並在我的構造函數中設置'var self = this;' – Voyna
您是否也可以在該問題中添加該部分?你是在構造函數中用'var'創建一個新的變量嗎?你不應該分配給你已經聲明的變量嗎? – Saravana