由于我想在Ionic 5 / Capacitor应用程序中使用位置信息,因此我在Geolocation API周围编写了包装器的第一个版本。
问题是,当我注入此服务并调用startReceivingLocationUpdates()
时,出现以下错误:
core.js:6014 ERROR TypeError: Cannot read property 'locationSubject' of undefined
at locationCallback (location.service.ts:51)
at window.navigator.geolocation.watchPosition.Object.enableHighAccuracy (geolocation.js:30)
at ZoneDelegate.invoke (zone-evergreen.js:359)
at Object.onInvoke (core.js:39699)
at ZoneDelegate.invoke (zone-evergreen.js:358)
at Zone.runGuarded (zone-evergreen.js:134)
at zone-evergreen.js:118
我的位置服务
import { Injectable } from '@angular/core';
import { Geolocation, GeolocationOptions, GeolocationPosition } from '@capacitor/core';
import { BehaviorSubject, Observable } from 'rxjs';
const locationOptions: GeolocationOptions = {
enableHighAccuracy: true,
requireAltitude: false
};
@Injectable({
providedIn: 'root'
})
export class LocationService {
private locationSubject = new BehaviorSubject<GeolocationPosition>(null);
private watchId: string = null;
constructor() {
}
receivingLocationUpdates(): boolean {
return this.watchId != null;
}
startReceivingLocationUpdates()
{
if(this.watchId !== null)
return;
this.watchId = Geolocation.watchPosition(locationOptions, this.locationCallback);
}
stopReceivingLocationUpdates()
{
if(this.watchId === null)
return;
Geolocation.clearWatch({id: this.watchId })
.then(_ => {
this.watchId = null;
});
}
subscribe(): Observable<GeolocationPosition>
{
return this.locationSubject.asObservable();
}
private locationCallback(location: GeolocationPosition) {
this.locationSubject.next(location);
}
}
我在做什么错?
这里的问题很可能是因为回调函数(locationCallBack)在与类不同的范围内执行而丢失了'this'所指向的内容。
要解决此问题,您应该绑定执行范围或使其透明。
尝试使用粗箭头功能:
private locationCallback = (location: GeolocationPosition) => {
this.locationSubject.next(location);
}