Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

angular

rxjs

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

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

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?

like image 524
cbierman Avatar asked Mar 12 '23 23:03

cbierman


1 Answers

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());
});

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:

  • Angular2 http retry logic
like image 86
Thierry Templier Avatar answered Apr 25 '23 20:04

Thierry Templier