如何在返回http.get之前等待异步数据

时间:2017-06-25 23:43:18

标签: angular typescript asynchronous

我正在使用ng2-ui-auth作为我的前端,我偶然发现了一个我不知道如何修复的问题...这是一个来自我的UserService的简单方法但是有一个问题 - 异步正在调用方法来获取http.get调用的必要标记。

getUser()
{
  const headers: Headers = new Headers();
  headers.append('Accept', 'application/json');
  headers.append('Content-Type', 'application/json');
  headers.append('X-Auth-Token', this.authService.getToken());

  const options = new RequestOptions({headers: headers});

  return this.http.get('http://localhost:9900/user', options).map(response => response.json());
}

问题是 - 有时在this.authService.getToken返回数据之前调用http.get,所以我在'X-Auth-Token'中得到一个null,因此给我留下了'Unauthorized'错误。

有没有办法等到标题完成然后返回http.get?

1 个答案:

答案 0 :(得分:1)

尝试使用promises和方法Then()来收集响应。像这样:

<div class='parents-parent'><div class='parent'><div style='width: 50%;background:green;'>A</div></div><div class='parent'><div style='width: 25%;background:red;'>B</div></div><div class='parent'><div style='width: 25%;background:blue;'>C</div></div></div>