【问题标题】:-Nativescript + Angular: Location and http post-Nativescript + Angular:位置和 http 帖子
【发布时间】:2021-03-15 18:00:33
【问题描述】:

我已经开始使用 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 函数的结果可用后发布请求。

谢谢大家!

【问题讨论】:

    标签: angular async-await geolocation nativescript angular2-nativescript


    【解决方案1】:

    您可以从地理定位插件返回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
           })
        }
      );
    }
    
    

    【讨论】:

    • 嗯,这正是我想要的,但我对 .then() 和 Promise 对象感到困惑......现在看起来很愚蠢:D
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-04-07
    • 2015-04-13
    • 1970-01-01
    • 2017-01-02
    • 2018-01-25
    • 2018-12-21
    相关资源
    最近更新 更多