2017-07-02 103 views
0

我刚刚从上周开始学习Ionic 2,现在我在服务中创建一个函数以返回我的API URL,它将检查localstorage是否存在任何令牌。如果是的话那么它会追加令牌自动将网址,下面是该函数的代码:Ionic 2服务函数在返回之前等待localstorage

getApiUrl(method: string){ 
    this.storage.get('user_data').then((val) => { 
     let extUrl: string = null; 
     if(val){ 
      extUrl = '?token='+val.token; 
      } 
     return "http://localhost/api/"+method+extUrl; 
    }).catch(err=>{ 
     console.log('Your data don\'t exist and returns error in catch: ' + JSON.stringify(err)); 
     return ''; 
    }); 
} 

但后来我通过调用这个函数在我的控制器:

this.http.post(this.service.getApiUrl("method_name"), data, options) 

出现下列错误:

Argument of type 'void' is not assignable to parameter of type 'string'. 

我曾试图改变我的代码,使用无极但似乎也没有工作,我怎样才能使我的功能等待API网址是什么?

回答

1

你没有从getApiUrl方法返回任何东西。你必须归还的承诺,你的承诺getApiUrl解决后,打电话给你的post方法:

getApiUrl(method: string){ 
    return this.storage.get('user_data').then((val) => { 
     let extUrl: string = null; 
     if(val){ 
      extUrl = '?token='+val.token; 
      } 
     return "http://localhost/api/"+method+extUrl; 
    }).catch(err=>{ 
     console.log('Your data don\'t exist and returns error in catch: ' + JSON.stringify(err)); 
     return ''; 
    }); 
} 

this.service.getApiUrl("method_name") 
    .then((url) => { 
    this.http.post(url, data, options); 
    }); 
+0

啊这种愚蠢的错误!非常感谢你! – Ping