我正在尝试测试一个简单的角8服务,该服务使用GeoLocation服务从角的Web获取用户位置
public enableGPS() {
if (!this.locationSubscription)
this.locationSubscription = this.geoLocationService.subscribe(
(position) => {
this._currentLocation = position.coords;
}
);
}这就是测试
describe("Toggle Location Service", () => {
it("should enable location service", () => {
const testPosition = {
position: {
coords: {
longitude: 1.0,
latitude: 2.0
}
}};
let geoLocationService: GeolocationService = TestBed.get(GeolocationService);
spyOn(geoLocationService, 'subscribe').and.returnValue(
Observable.of(testPosition));
service.enableGPS();
expect(service.currentLocation).toEqual(testPosition);
});
});但是service.currentLocation总是未定义,并且订阅回调从不被调用。
发布于 2022-05-17 16:56:39
我不知道现在回答你的问题是否为时已晚,但我只是发现自己需要在我的项目中使用这个。
因为我不能让库工作,所以直接使用浏览器的资源。
https://developer.mozilla.org/en/docs/Web/API/Geolocation/getCurrentPosition
我创建了一个服务,如下所示:
import { Injectable } from '@angular/core';
@Injectable({
providedIn: 'root'
})
export class LocationService{
constructor(){
}
getPosition(): Promise<any> {
return new Promise((resolve, reject) => {
navigator.geolocation.getCurrentPosition(resp => {
resolve({lng: resp.coords.longitude, lat: resp.coords.latitude});
},
err => {
reject(err);
});
});
}
}然后我在我的组件中称之为:
import { LocationService } from '../Interfaces/Services/location.service';
location : any = { latitude: '', longitude: '' };
constructor(
private _locationService: LocationService
) {
}
async getLocation() {
this._locationService.getPosition().then(pos => {
this.location= {
latitude: pos.lat,
longitude: pos.lng
}
});
}我希望它对你有帮助,如果没有,我希望未来的开发人员能清楚地找到答案。
https://stackoverflow.com/questions/70653242
复制相似问题