我正在使用离子2并且有类如下的类。我正在使用locationServices插件,不想使用离子原生地理定位插件。
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 :(得分:0)
首先,您不再需要let self = this;
技术,只需使用TypeScript的lambda语法() => {}
而不是匿名函数来访问this
(您的类实例)一个“)在lambdas的深处。
然后,确保您正在检查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);
}
}
希望它有所帮助。