I am passing the latitude and longitude to a service from a component. And after doing some work in the service, I want to pass the value in isOnsite
to my component. Depending on that value, I want to bring up another page.
My problem:
When I get the returned value in the component, it is only undefined
as the service runs asynchronously. What can I change in my code to get the correct value in my component? Below is my code. (isAtSite computes some math and returns a boolean).
Also is there a way to push to the page stack from the service?
location.service.ts
getDeviceCoords(map, destLat, destLng) {
this.mapInstance = map;
this.geolocation.getCurrentPosition().then((pos) => {
new google.maps.LatLng(pos.coords.latitude, pos.coords.longitude);
let deviceLat = pos.coords.latitude;
let deviceLng = pos.coords.longitude;
let isOnSite = this.isAtSite(deviceLat, deviceLng, destLat, destLng);
return isOnSite;
}, (err) => {
console.log(err);
});
}
map.component.ts
getDeviceCoords(){
let isOnSite = this.geolocationProvider.getDeviceCoords(this.map, this.lat, this.lng);
console.log("isOnSite (map.ts) =>" + isOnSite); //undefined. Should be boolean
}
It is undefined because you didnt return anything from the function getDeviceCoords(map, destLat, destLng)
(that equals to return undefined)
return isOnSite
inside getDeviceCoords
really returns not from getDeviceCoords
, but from callback passed to then
- (pos) => {}
So, first of all, you must return promise from getDeviceCoords
:
getDeviceCoords(map, destLat, destLng) {
this.mapInstance = map;
return this.geolocation.getCurrentPosition().then(...your code);
}
And then in your component you can use it like
getDeviceCoords() {
this.geolocationProvider.getDeviceCoords(this.map,this.lat, this.lng)
.then(isOnSite => // your value can be accessed here);
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.