Angular2打字稿承诺

时间:2017-04-18 14:33:05

标签: angular typescript promise

我希望有一个通用的http get服务,我使用以下代码完成:

public get(module: String): Promise<any> { 
return this.http.get(module)
           .toPromise()
           .then(response => response.json().data as Any[])
           .catch(this.handleError);}

现在的问题是,现在我想知道何时完成http.get以发出命令,我不知道该怎么做。

如果我在.then步骤中添加了一些东西,它就不起作用

.then(response => response.json().data as Any[] && alert("HI"))

如果我在另一个.then之后添加then,则会在http请求完成之前触发。

我怎样才能实现它?

使用dfsq代码我能够发出警报(&#34; HI&#34;)但响应未定义。这是我使用它的方式:

this.dataService.get(&#34; myurl&#34;)。then(response =&gt; console.log(response));

我未定义

1 个答案:

答案 0 :(得分:1)

您确实需要再添加一个then块:

public get(module: String): Promise<any> { 
  return this.http.get(module)
           .toPromise()
           .then(response => response.json().data as Any[])
           .then(data => {
             alert("HI") // <---- do something here
             return data
           })
           .catch(this.handleError);
}

确保从那时块中返回先前的data,然后将其传递到承诺链下方。