【问题标题】:Angular2 typescript promiseAngular2打字稿承诺
【发布时间】:2017-04-18 22:58:01
【问题描述】:

我想要一个通用的 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 代码我可以触发 alert("HI") 但响应未定义。这是我使用它的方式:

this.dataService.get("myurl").then(response => console.log(response));

我没有定义

【问题讨论】:

  • "如果我在另一个之后添加一个 .then,它会在 http 请求完成之前触发。"你能显示这段代码吗?这不是承诺链的工作方式
  • @suraj 我猜是then(alert("Hi"))

标签: angular typescript promise


【解决方案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);
}

确保从 then 块返回之前的 data,以便将其进一步传递到 Promise 链。

【讨论】:

  • 对不起 dfsq,警报(“HI”)正在工作,但现在响应不起作用。这是为什么?我从 console.log 得到未定义
  • response 在 get 函数中返回响应。但函数外返回未定义。
  • 你把console.log具体放在哪里?
猜你喜欢
  • 1970-01-01
  • 2020-03-10
  • 2018-12-19
  • 2019-08-24
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多