简体   繁体   English

Angular 2 - 当Http请求依赖于另一个Http请求的结果时该怎么办

[英]Angular 2 - What to do when an Http request depends on result of another Http request

I'm having trouble figuring out how to use the result of an Http request to make another Http request. 我无法弄清楚如何使用Http请求的结果来发出另一个Http请求。

I have a Service that requests and receives JSON Web Tokens from a backend API that looks like: 我有一个服务,它从后端API请求和接收JSON Web令牌,如下所示:

@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 || "";
  }

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? 我现在如何使用requestToken() (一个Observable)的结果进行另一个API调用,使用JWT进行身份验证,并从中获取结果? Or maybe more simply, what do you do when one Http call depends on the result of another? 或者更简单地说,当一个Http调用依赖于另一个Http调用的结果时,你会怎么做?

You could use the flatMap operator to do that: 您可以使用flatMap运算符来执行此操作:

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

What you could also do is to make this transparent by extending the HTTP class. 您还可以做的是通过扩展HTTP类使其透明。 In it, you could check the token validity and if it's expired, call the requestToken method. 在其中,您可以检查令牌有效性,如果它已过期,请调用requestToken方法。

See this question for more details: 有关详细信息,请参阅此问题:

You can for example use the switchMap operator if you have a network call that needs to use the result of a previous network call: 例如,如果您的网络呼叫需要使用先前网络呼叫的结果,则可以使用switchMap运营商:

const combined$ = jwtAuthenticationService.requestToken()
    .switchMap(tokenBody => this.http.get('/someurl') );

This is the marble diagram: 这是大理石图:

// requestToken

|---------------T---| 

// second HTTP request

                   |------R--|

// combined$

|--------------------------R--|

The sequence goes like this: 顺序如下:

  • subscription to requestToken occurs 订阅requestToken发生
  • token returns, first call observable completes 令牌返回,第一次调用observable完成
  • the result of requestToken is taken and the initial Observable is transformed via switchMap into a second Observable 取得requestToken的结果,并通过switchMap将初始Observable转换为第二个Observable
  • if the initial observable had not completed, combined$ would have unsubscribed from it 如果最初的观察结果尚未完成,那么combined$将取消订阅
  • a second observable is made for the second network call, that uses the result of the first 第二个网络调用是第二个可观察的,它使用第一个的结果
  • second call returns, second observable completes, combined$ completes 第二次调用返回,第二次观察完成, combined$完成

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM