gpt4 book ai didi

angular - typescript 函数抛出错误以返回值

转载 作者:太空狗 更新时间:2023-10-29 18:20:09 24 4
gpt4 key购买 nike

这就是我想要完成的,我正在调用函数 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;
});
}

我可能在这里遗漏了一个非常基本的概念。我们将不胜感激。

最佳答案

您需要在此处返回地理定位的Promise

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

关于angular - typescript 函数抛出错误以返回值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44691323/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com