2017-07-02 108 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