打字稿:延迟后的返回值

时间:2016-08-27 11:15:49

标签: angular typescript

我有一个获取请求,这是一个asynchornouns方法。要获取数据,我会延迟3秒,然后我希望返回结果。以下是代码:

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

2 个答案:

答案 0 :(得分: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)
}

答案 1 :(得分:0)

您无法从异步操作返回值(除非您使用ES2017的新async / await功能),但您有两个选择:

(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);
            });
    });
}
相关问题