我正在开发一个简单的POC来显示当前位置。 程序从geolocation.watchLocation接收信息,但是在我按下STOP Monitoring按钮之前,该位置没有绑定并显示在屏幕上。需要注意的是,日志正确显示了坐标
JS: Start Monitoring ...
JS: Location: 49.6411839:6.0040451
JS: Stop Monitoring ...
import {Component} from "@angular/core";
import {Router} from "@angular/router";
import geolocation = require("nativescript-geolocation");
@Component({
selector: "TrackingPageSelector",
template:`
<StackLayout>
<Button [text]="watchId==0 ? 'Start Monitoring' : 'Stop Monitoring'" (tap)="buttonStartStopTap()"></Button>
<Label class="labelValue" [text]="latitude"> </Label>
<Label class="labelValue" [text]="longitude"> </Label>
</StackLayout>`
})
export class TrackingPageComponent {
latitude: number = 0;
longitude: number = 0;
watchId: number = 0;
constructor(private router: Router) {}
ngOnInit() {
if (!geolocation.isEnabled()) geolocation.enableLocationRequest();
}
public buttonStartStopTap() {
if (this.watchId != 0) {
console.log('Stop Monitoring ...');
geolocation.clearWatch(this.watchId);
this.watchId = 0;
} else {
console.log('Start Monitoring ...');
let _self = this;
this.watchId = geolocation.watchLocation(
function (loc) {
if (loc) {
_self.latitude = loc.latitude;
_self.longitude = loc.longitude;
console.log(`Location: ${_self.latitude}:${_self.longitude}`);
}
},
function(e){
this.errorMsg = e.message;
},
{desiredAccuracy: 3, updateDistance: 10, minimumUpdateTime: 1000 * 3}); // Should update every X seconds
}
}
}
答案 0 :(得分:2)
如果您使用()=>
代替function ()
,那么您就不需要_self
黑客攻击。
看起来您需要手动调用更改检测。 NgZone似乎不会涵盖geolocation.watchLocation()
constructor(private cdRef:ChangeDetectorRef) {}
...
this.watchId = geolocation.watchLocation(
(loc) => {
if (loc) {
this.latitude = loc.latitude;
this.longitude = loc.longitude;
this.cdRef.detectChanges();
console.log(`Location: ${this.latitude}:${this.longitude}`);
}
},
(e) => {
this.errorMsg = e.message;
},
或者zone.run(() => ...)
喜欢
constructor(private zone:NgZone) {}
...
this.watchId = geolocation.watchLocation(
(loc) => {
if (loc) {
this.zone.run(() => {
this.latitude = loc.latitude;
this.longitude = loc.longitude;
console.log(`Location: ${this.latitude}:${this.longitude}`);
});
}
},
(e) => {
this.errorMsg = e.message;
},
如果您只更改本地字段cdRef.detectChanges()
是更好的选择,如果您调用的方法可能会修改当前组件之外的某些状态,zone.run(...)
是更好的选择。