Búsqueda de sitios web

angular - función de TypeScript que lanza un error al devolver un valor


Aquí está lo que estoy intentando lograr, estoy llamando a una función getGeoLocationOfUser() que se supone me devuelve la geolocalización del usuario y la función se supone que debe devolver solo cuando la geolocalización está disponible o hay algún error.

pero la función anterior está generando un error Una función cuyo tipo declarado no es ni 'void' ni 'any' debe devolver un valor.

  public userGeolocation={latitude:null,longitude:null}

  getGeoLocationOfUser():{latitude:any,longitude:any}{
    this.geolocation.getCurrentPosition().then((resp) => {
    this.userGeolocation.latitude=resp.coords.latitude;
    this.userGeolocation.longitude=resp.coords.longitude;
    console.log(this.userGeolocation);

localStorage.setItem('userGeoLocation',JSON.stringify(this.userGeolocation));
return this.userGeolocation;
 //saving geolocation of user to localStorage

 }).catch((error) => {
  console.log('Error getting location', error);
  return this.userGeolocation;
});
}

Podría estar perdiéndome un concepto muy básico aquí. Se agradecerá cualquier ayuda.

Respuesta #1

Necesitas devolver una Promise de Geolocalización aquí.

//Make return type as Promise<object_type> or Promise<any>
 getGeoLocationOfUser():Promise<{latitude:any,longitude:any}>{
   //return the inner function
    return this.geolocation.getCurrentPosition().then((resp) => {
    this.userGeolocation.latitude=resp.coords.latitude;
    this.userGeolocation.longitude=resp.coords.longitude;
    console.log(this.userGeolocation);

localStorage.setItem('userGeoLocation',JSON.stringify(this.userGeolocation));
return this.userGeolocation;
 //saving geolocation of user to localStorage

 }).catch((error) => {
  console.log('Error getting location', error);
  return this.userGeolocation;
});
}

Luego puedes obtener el valor llamando a function().then(callback).

 getGeoLocationOfUser().then( loc =>{
     this.location = loc}).catch(err=>{});

Respuesta #2

Por favor, cambie el tipo de retorno any en lugar de {latitude:any,longitude:any}

getGeoLocationOfUser(): any {
      return  this.geolocation.getCurrentPosition().then((resp) => {
            this.userGeolocation.latitude = resp.coords.latitude;
            this.userGeolocation.longitude = resp.coords.longitude;
            console.log(this.userGeolocation);
            localStorage.setItem('userGeoLocation', JSON.stringify(this.userGeolocation));
            return this.userGeolocation;
            //saving geolocation of user to localStorage
        }).catch((error) => {
            console.log('Error getting location', error);
            return this.userGeolocation;
        });
} 

Artículos relacionados