【问题标题】:Angular 2 - Wait for Promise before continuingAngular 2 - 在继续之前等待承诺
【发布时间】:2017-07-31 23:02:15
【问题描述】:

我需要创建一个地理位置变量并将值发送到 API,但我很麻烦。

public virtualRegistrationHandler(e: any): void {
    e.preventDefault();
    console.log("loop");
    if (navigator.geolocation) {
        let geoLoc = navigator.geolocation.getCurrentPosition(this.setGeoLoc);

        this.VirtualRegistrationService.virtualRegistration(geoLoc)
            .subscribe(
            response => this.toastyCommunicationService.addSuccesResponseToast(response),
            error => this.toastyCommunicationService.addErrorResponseToast(error)
            );
    } else {
        this.toastyCommunicationService.addErrorResponseToast("Geolocation is not supported by this browser.");
    }
}

private setGeoLoc(position: any) {
    console.log("Latitude " + position.coords.latitude, "Longitude " + position.coords.longitude);
    let geoLoc = { "Latitude": position.coords.latitude, "Longitude": position.coords.longitude };
    return geoLoc;
}

这是我当前的代码,但它不会等待返回 geoLoc,所以现在它会向 API 发送一个未定义的参数。

我想 API 调用等到geoloc 被设置。

我做了一些谷歌搜索,得到了一些承诺,但是我在编写语法时遇到了麻烦,我找不到任何可行的示例。

如何正确编写代码,以便在我的函数继续使用 API 之前必须先设置 geoLoc?

【问题讨论】:

    标签: angular promise angular-promise


    【解决方案1】:

    根据this,getCurrentPosition方法返回一个promise,所以你只需要订阅它。

    类似:

    navigator.geolocation.getCurrentPosition(
        pos=>{
      var crd = pos.coords;
    
      console.log('Your current position is:');
      console.log(`Latitude : ${crd.latitude}`);
      console.log(`Longitude: ${crd.longitude}`);
      console.log(`More or less ${crd.accuracy} meters.`);
        },
        onError=>{
        ...Catch errors...
        }
        );
    

    【讨论】:

    • 我认为你在正确的轨道上,但是 "Latitude": position.coords.latitude 它说它不知道 position 是什么,那么我如何获得这个值?
    • resove 函数应该保存一个类型为 position (developer.mozilla.org/en-US/docs/Web/API/Position) 的对象。我已经编辑了我的答案,这样会更清楚
    【解决方案2】:

    您可以将navigator.geolocation.getCurrentPosition 调用转换为 Promise:

    const whenPositionGet = new Promise((resolve, reject) => navigator.geolocation.getCurrentPosition(resolve, reject));
    whenPositionGet.then(
      (position: Position) => {
          console.log("Latitude " + position.coords.latitude, "Longitude " + position.coords.longitude);
      },
      (error: PositionError) => {
          console.error(error);
      }
    );
    

    【讨论】:

      猜你喜欢
      • 2018-12-14
      • 1970-01-01
      • 2018-01-17
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-05-21
      • 2020-06-24
      • 2020-01-15
      相关资源
      最近更新 更多