Search code examples
angularhttpclientangular-httpclient

Dependent HTTP calls in angular service


I am calling secured REST API's from angular service. In this case I have to get token once before calling any API as pass it as a part of HTTP Header. But when ever I am calling any function from my component I am getting app_token as undefined. This is due to async call to token_api. Next call gets successes as earlier call fetches value for token from server.

I have added async-await to get_token function, but in vain.. Any advice on how to handle this situation.

private app_token;

private getToken(){    
    if (this.token == undefined) {
      console.log("getting new token");
      return this.httpClient.post<Token>(this.TOKEN_API, body, options)
        .pipe(retry(3), catchError(this.handleError))
        .subscribe(data => {
            console.log(data[0].username);
            return this.app_token = data;
        });
    }
}

public getEmployee{
    this.getToken();

    const headers = new HttpHeaders()
      .set('Authorization', 'Bearer ' + this.app_token );

    const options = {
      headers: headers
    };

    return this.httpClient.get(this.EMP_API, options)
      .pipe(retry(3), catchError(this.handleError));
}

public getDepartments{
    this.getToken();

    const headers = new HttpHeaders()
      .set('Authorization', 'Bearer ' + this.app_token );

    const options = {
      headers: headers
    };

    return this.httpClient.get(this.DEPT_API, options)
      .pipe(retry(3), catchError(this.handleError));
}

Solution

  • Finally, I found solution for this issue. Here I am using RxJS Pipe and concatMap functions to execute 2 http request and passing output of one request to other.

      return this.getToken().pipe(
        concatMap((tokenData)=> {
          headers = headers.append('Authorization', 'Bearer ' + this.token.access_token);
    
          return this.httpClient.get(url, { headers: headers })
            .pipe( retry(3), catchError(this.handleError));
        })
      );