2017-02-10 12 views
1

我正在使用ionic 2並擁有類似以下的類。我正在使用locationServices插件,不想使用離子本地地理位置插件。數據成員的值在Typescript中沒有改變

export class a{ 
    location_acquiring:boolean; 
    location_available:boolean; 
    constructor(){ 
     this.location_acquiring=true; 
     this.location_available=false; 
    }    
    fun(){ 
     //Here i am using some cordova plugins and setting the location latitude and longitude localstorage variables. 
     let self=this; 
     cordova.plugins.diagnostic.isLocationEnabled(function(enabled){          
      let selfa=self; 
      cordova.plugins.diagnostic.isLocationAvailable(function(available){ 
       let selfb=selfa; 
       cordova.plugins.locationServices.geolocation.watchPosition(function(position) { 
        //Now here although project is build without errors. but the values of the variables are not updated. 
        selfb.location_acquiring=false; 
        selfb.location_available=true; 
       },function(error){}); 
      },function(error){}); 
     },function(error){}); 
    } 
    show_values(){ 
     console.log(this.location_acquiring); 
     console.log(this.location_available); 
    } 
} 

locationServices插件內部的變量更改不會反映在類變量中。

show_values()功能

真正的輸出

+0

未經測試且可能不相關,但對於Google地圖API,您需要明確地在zone.js中運行一些回調。如果你嘗試在構造函數中注入'private __zone:NgZone'(NgZone生活在angular/core中),然後執行:this._zone.run(()=> {self_location_acquiring = false; selfb。 location_available = true; });' –

回答

0

首先,你不需要到let self = this;技術了,只是用打字稿的lambda語法() => {}代替匿名函數,以訪問this (您的類「a」的實例)深入lambda表達式。

然後,確保您檢查Cordova插件調用中是否發生錯誤(例如,通過將錯誤輸出到調試控制檯),從而確保您的成功回調代碼不會執行。

嘗試用下面的代碼:

export class a{ 
    location_acquiring: boolean = true; 
    location_available: boolean = false; 

    fun(){ 
    //Here i am using some cordova plugins and setting the location latitude and longitude localstorage variables. 
    cordova.plugins.diagnostic.isLocationEnabled((enabled) => { 
     cordova.plugins.diagnostic.isLocationAvailable((available) => { 
      cordova.plugins.locationServices.geolocation.watchPosition(function(position) { 
       //Now here although project is build without errors. but the values of the variables are not updated. 
       this.location_acquiring=false; 
       this.location_available=true; 
      }, function(error){ 
       console.error('[watchPosition]', error); 
      }); 
     }, (error) => { 
      console.error('[isLocationAvailable]', error); 
     }); 
    }, (error) => { 
     console.error('[isLocationEnabled]', error); 
    }); 
    } 

    show_values(){ 
    console.log(this.location_acquiring); 
    console.log(this.location_available); 
    } 
} 

希望它能幫助。