Angular 2-当一个Http请求依赖于另一个Http请求的结果时该怎么办 [英] Angular 2 - What to do when an Http request depends on result of another Http request

查看:198
本文介绍了Angular 2-当一个Http请求依赖于另一个Http请求的结果时该怎么办的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在弄清楚如何使用Http请求的结果来发出另一个Http请求时遇到了麻烦.

I'm having trouble figuring out how to use the result of an Http request to make another Http request.

我有一个服务,该服务从如下所示的后端API请求并接收JSON Web令牌:

I have a Service that requests and receives JSON Web Tokens from a backend API that looks like:

@Injectable()
export class JwtAuthorizationService {

  constructor(private http: Http) {}

  public requestToken(): Observable<string> {
    // Set dummy credentials.
    let body = this.setBody();
    let headers = this.setHeaders();
    let token = this.http.post(tokenUrl, body, { headers: headers })
      .map(this.extractData)
      .catch(this.handleError);

    // Return the Observable
    return token;
  }

  private extractData(res: Response): string {
    let body = res.text();
    return body || "";
  }

我现在如何使用requestToken()(一个可观察的)的结果进行另一个通过JWT进行身份验证的API调用,并从中获取结果?或者更简单地说,当一个Http调用依赖于另一个Http的结果时,您该怎么办?

How can I now use the result of the requestToken() (an Observable) to make an another API call, authenticated with the JWT, and get the result back from that? Or maybe more simply, what do you do when one Http call depends on the result of another?

推荐答案

您可以使用flatMap运算符来做到这一点:

You could use the flatMap operator to do that:

this.authorizationService.requestToken().flatMap(token => {
  var headers = new Headers();
  headers.append('Authorization', `Bearer ${token}`);
  return this.http.get('...', { headers }).map(res => res.json());
});

您还可以做的是通过扩展HTTP类来使其透明.在其中,您可以检查令牌的有效性,如果令牌已过期,请调用requestToken方法.

What you could also do is to make this transparent by extending the HTTP class. In it, you could check the token validity and if it's expired, call the requestToken method.

有关更多详细信息,请参见此问题:

See this question for more details:

这篇关于Angular 2-当一个Http请求依赖于另一个Http请求的结果时该怎么办的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆