2017-04-18 126 views
1

我想有一个通用的HTTP GET服务,我这样做是使用下面的代码:Angular2打字稿承诺

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(response => response.json().data as Any[] && alert("HI")) 

如果我在其他then后添加.then,它触发被满足的HTTP请求之前。

我该如何实现它?

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

this.dataService.get(“myurl”)。then(response => console.log(response));

我得到了一个未定义

+0

“如果我在其他时间之后添加一个.then,它会在满足http请求之前触发。”你能显示这个代码吗?这不是如何承诺链接工程 –

+0

@suraj我想它是'然后(警报(“嗨”))'。 – dfsq

回答

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,那么块,所以你进一步传递下来的诺言链。

+0

对不起dfsq,警报(“HI”)正在工作,但现在响应不起作用。这是为什么?我得到了来自console.log的未定义的 – tunoandsuno

+0

响应里面的get函数返回响应。但是在函数外面返回undefined。 – tunoandsuno

+0

你把console.log放在哪里? – dfsq