Nicolas
Nicolas

Reputation: 4756

Angular 2 - Wait for Promise before continuing

I'm need to create a geolocation variable and send the values to an API but I'm trouble.

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

this is my current code, but it doesn't wait for geoLoc to be returned, so right now it sends an undefined parameter to the API.

I want to API call to wait untill geoloc is set.

I did some googling and I came accros promises, however I'm having trouble writing the syntax and I cant find any working example.

How do I correctly write my code so that geoLoc has to be set first before my function continues to the API?

Upvotes: 3

Views: 3847

Answers (2)

Gili Yaniv
Gili Yaniv

Reputation: 3221

According to this, The getCurrentPosition method returns a promise, So you only need to subscribe to it.

Something like :

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

Upvotes: 2

Aleksandr Petrovskij
Aleksandr Petrovskij

Reputation: 1243

You can convert navigator.geolocation.getCurrentPosition call to 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);
  }
);

Upvotes: 2

Related Questions