2017-08-09 90 views
2

我有一個Ionic 2應用程序,以列表的形式顯示包內的用戶項目。我創建了一個函數來檢索Package中的當前Item索引,它被觸發,用戶啓動應用程序。它檢查Ionic Storage(內部)存儲器中的索引名稱 - 值對是否爲空。在這種情況下,索引設置爲0並存儲在內部和工作存儲器中。否則,從內部存儲器中檢索索引並用於設置工作存儲器。Ionic Storage在承諾中未定義?

但是,在下面的代碼中self.storage.set(myString, '0');會引發錯誤TypeError: Cannot call method 'set' of undefined。我使用console.dir進行了檢查,實際上self.storagethen(...);區塊內未定義。這是爲什麼,我該如何解決它?

進口,報關,構造

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'); 
      } 
     ) 
    }); 
} 
+0

你在哪裏設置'self'? – Saravana

+0

我聲明它低於我的導入,並在我的構造函數中設置'var self = this;' – Voyna

+1

您是否也可以在該問題中添加該部分?你是在構造函數中用'var'創建一個新的變量嗎?你不應該分配給你已經聲明的變量嗎? – Saravana

回答

0

我相信,爲什麼發生這種情況的原因是因爲全局變量self在每一個頂部聲明我的網頁和服務。這意味着當我運行self.storage.get(myString)時,ItemStorageService的構造函數正在運行並重新初始化self以指向它自己。

解決方案不是在任何地方都使用self,而只是在需要它的地方(如內部回調函數)並確保將self = this設置爲儘可能接近其使用位置。

0

嘗試刪除self = this並僅使用this

像:

this.packageIndex = 0;this.storage.get(myString).then(...