2016-08-27 63 views
0

我有一個獲取請求,這是一個asynchornouns方法。到的數據,我做了3秒的延遲,之後,我希望返回結果。下面是代碼:Typescript:延遲後的返回值

getWeatherForcastWithLocation(){ 

      this._http.get(uri) 
        .subscribe(res =>this.setItems(res.json(),false)); 
      setTimeout(()=>{ 
        return this.weatherStatatistic; 
      },3000);   

    return null; 
} 

我想回this.weatherStatatistic,但是,它總是返回null。我知道這是因爲方法結束時return null;,但是如果我刪除它,方法的返回類型將爲void。 所以我該如何返回this.weatherStatistic

+0

'this.setItems'會發生什麼? – cYrixmorten

+0

它只是在weatherStatistic中設置json值 – Salman

+0

順便說一句,認爲你應該閱讀承諾的概念。通常你會返回這個._ $ http請求,並得到類似'this這樣的響應。 getWeatherForcastWithLocation()。then((res)=> {})'在大括號內處理響應。 – cYrixmorten

回答

1

您應該將函數包裝到promise或observable中。或者更簡單的只是返回http請求,另一端設置超時。

事情是這樣的:

getWeatherForcastWithLocation(){ 
    return this._http.get(uri).map(res => this.setItems(res.json(),false)) 
} 

// In the receiving funtion 
someFunction() { 
    setTimeout(() => /* code to execute */, 3000) 
} 
0

不能從異步操作返回一個值(除非您使用新的異步/等待的ES2017功能),但你有兩個選擇:

( 1)傳遞一個回調以接收數據時,準備就緒:

getWeatherForcastWithLocation(cb: (stats: any) => void) { 
    this._http.get(uri) 
     .subscribe(res => { 
      this.setItems(res.json(), false); 
      cb(this.weatherStatatistic); 
     }); 
} 

(2)返回一個承諾的數據:

getWeatherForcastWithLocation(): Promise<any> { 
    return new Promise((resolve, reject) => { 
     this._http.get(uri) 
      .subscribe(res => { 
       this.setItems(res.json(), false); 
       resolve(this.weatherStatatistic); 
      }); 
    }); 
}