2017-05-29 49 views
0

我正在用Ionic 2編寫一個應用程序,並且取得了很好的進展,但是我只是掛斷了一些我認爲可能是一個簡單的修復。Ionic 2 setInterval變量範圍

我在屏幕上有文字,5秒後我想更新屏幕上的文字。我似乎無法訪問setInterval函數中的變量。

constructor(public nav: NavController, private navParams: NavParams, private getserver: GetServerService, storage: Storage) { 
    this.storage = storage; 

    this.storage.get('userAuth').then((name) => { 
     if(name.id === undefined) { 
      this.nav.setRoot(LoginPage); //kick back to login if no userdata 
     }else{ 

      let options = {timeout: 120000, enableHighAccuracy: true}; 
      navigator.geolocation.getCurrentPosition((position) => { 

      this.driverStatus = 'hi'; 

      setInterval(()=> { 
       this.driverStatus = 'Updated Text'; 
      }, 2000); 

      }, 
      (error) => { 
      console.log(error); 
      }, 
      options 
     ); 
     } 
    }); 

    } 

} 

當我運行該應用程序時,它顯示文本「你好」,但從不更新文本爲「更新文本」。控制檯正確顯示輸出。

我已經嘗試了Ionic2 function setInterval can't get a parameter的建議,但這些建議也無效。我的其他失敗嘗試如下。

var that = this; 
setInterval(function() { 
    that.userText = 'Updated Text'; 
}, 2000); 

setInterval(()=> { 
    this.userText = 'Updated Text'; 
}, 2000); 

回答

0

這是一些關於從角2 這個區域已經討論here 您可以通過注入NgZone的對象,並調用它的run()方法修復它

setInterval(()=> { 
    this.ngZone.run(() => { 
     this.userText = 'Updated Text'; 
    }); 
}, 2000); 
+0

感謝您的回覆。我想我必須包含另一個文件才能讓ngZone工作。它沒有用完。 我意識到我已經有了我需要的前一個窗口可用的gps座標(生成一張地圖),所以我只是將這些座標存儲到這個頁面上,這就消除了我的問題。它也加快了應用程序的發展。 –

+0

你必須在你的組件中輸入它,然後在構造函數中注入它。 –