打字稿函数抛出错误以返回值



这是我试图完成的,我调用了一个函数getGeoLocationOfUser((,我应该向我返回用户的地理位置,并且函数应该仅在地理位置可用或存在一些错误时才返回。

但上面的函数抛出了一个错误 声明类型既不是"void"也不是"any"的函数必须返回一个值。

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

我可能在这里错过了一个非常基本的概念.任何帮助将不胜感激。

您需要在此处返回地理位置承诺

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

然后,可以通过调用 function().then(callback) 来获取该值。

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

请将返回类型更改为any而不是{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;
        });
} 

您可以尝试使用any返回类型。

getGeoLocationOfUser(): Promise<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;
});
}

相关内容

  • 没有找到相关文章

最新更新