typescript函数抛出错误返回一个值

时间:2017-06-22 06:03:49

标签: angular typescript ionic2

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

我可能在这里错过了一个非常基本的概念。任何帮助都将受到赞赏。

3 个答案:

答案 0 :(得分:3)

您需要在此处返回Geolocation的 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=>{});

答案 1 :(得分:1)

请更改返回类型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;
        });
} 

答案 2 :(得分:0)

您可以尝试使用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;
});
}