-Nativescript + Angular: 位置和 http post

-Nativescript + Angular: Location and http post

我已经开始使用 Angular 在 NativeScript 上开发应用程序。我已经成功地构建了一个服务器来响应我来自 Nativescript 应用程序的 get/post 请求,但是我在发送一些信息时遇到了困难。

我的应用程序必须完成的任务之一是通过 GPS 定位用户,然后将其发送到 API 进行存储。我的问题是代码在收到定位函数的结果之前尝试发送它。

我的导入是这样的

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

我用来获取用户位置的函数如下所示:

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
  })
}

所以我想使用这个函数检索经度和纬度(我已经测试过它可以工作)然后将它们发送到我的api。

我已经阅读了有关 Promises、Observables 和 async/await 的内容,但目前需要时间并限制我的功能是位置功能,而不是服务器通信功能。所以我想我的问题是,一旦 getLocation 函数的结果可用,我不知道如何等待我的 getLocation 函数以便 post 请求 post 它。

谢谢大家!

您可以 return 来自地理定位插件的 Promise 并使用 then 接线员等待呼叫。

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

并在调用 api 时像这样使用它

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