Search code examples
angularasync-awaitgeolocationnativescriptangular2-nativescript

-Nativescript + Angular: Location and http post


I have started to develop an app on NativeScript using Angular. I have successfully build a server that responds to my get/post requests from the Nativescript app, but I'm struggling sending some information.

One of the tasks my app has to do is to locate the user via GPS and then send it to the API to store it. My problem is that the code tries to send it before receiving the result of the location function.

My imports look like this

import * as geolocation from "nativescript-geolocation";
import { Accuracy } from "ui/enums";

And the function I'm using to get the users' location looks like this:

getLocation() {
  console.log('Getting location');
  geolocation.getCurrentLocation({
    desiredAccuracy: Accuracy.high,
    maximumAge: 5000,
    timeout: 20000
  }).then(res => {
    this.lat = res.latitude;
    this.lon = res.longitude;
    console.log('Located!');
    return res
  })
}

So I want to retrieve longitude and latitude using this function (I have tested that it works) and then send them to my api.

I have read about Promises, Observables and async/await but the function that takes time and is limiting me at the moment is the location one, not the server communication one. So I guess my problem is that I don't know how to await my getLocation function in order for the post request to post it once the result of the getLocation function is available.

Thanks everyone!


Solution

  • You can return the Promise from the geolocation plugin and use a then operator to wait for the call.

    getLocation() {
      console.log('Getting location');
      return geolocation.getCurrentLocation({
        desiredAccuracy: Accuracy.high,
        maximumAge: 5000,
        timeout: 20000
      });
    }
    

    and use it like this when making the api call

    sendLocation() {
      this.getLocation().then(
        res => {
           this.http.post(URL, {
             lat: res.latitude,
             lon: res.longitude
           })
        }
      );
    }