【问题标题】:How to wait for asynchronous data before returning http.get如何在返回http.get之前等待异步数据
【发布时间】:2017-06-26 07:47:54
【问题描述】:

我正在为我的前端使用 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());
}

问题是 - 有时 http.get 在 this.authService.getToken 返回数据之前被调用,所以我最终在“X-Auth-Token”中得到一个空值,从而给我留下一个“未经授权”的错误。

有没有办法等到header完成后再返回http.get?

【问题讨论】:

  • 我认为这必须重构,以便 getUser() 本身返回一个 Promise。您可以将 authService 调用放在 Promise 中,然后使用 then 执行其余代码。
  • getToken() 是网络服务吗?它调用一个http请求

标签: angular typescript asynchronous


【解决方案1】:

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

getUser()
{
  const headers: Headers = new Headers();
  headers.append('Accept', 'application/json');
  headers.append('Content-Type', 'application/json');

  //Collect token value
  this.authService.getToken().then(function(resp){
      headers.append('X-Auth-Token', resp);
  });

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

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

【讨论】:

  • 感谢您的回复。问题是 this.authService.getToken() 是 String 类型,因此我不能使用我们订阅的任何方法,例如。我试图在获得 Facebook 授权后立即调用 getUser,似乎在登录和 AuthService 之间需要一段时间才能准备好传送数据:/
  • hmmm,另一种方法就像你说的那样,在收集令牌之后实现 getUser 并用一些承诺实现包装这个 authService.getToken 方法。那个方法是你的吧?
猜你喜欢
  • 1970-01-01
  • 2014-11-26
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-05-25
  • 2019-06-17
  • 2020-04-20
  • 1970-01-01
相关资源
最近更新 更多