0

I am new to Angular/RxJS etc. I want to make two HTTP requests sequentially. I assumed if I call the next method in the complete function of first observable it should run sequentially, but that is not the case.

login(): boolean {
let windowsAuthToken: string;

var result = this.http.get(this.authUrl).subscribe(
  (response: any) => {
    windowsAuthToken = response.token;
  },
  err => {},
  () => {
    return this.performWindowsAuthentication(windowsAuthToken);
  }
);
return false;
}

performWindowsAuthentication(windowsAuthToken: string): boolean {
if (!!windowsAuthToken) {
  const loginRequest = new WindowsLoginRequest(windowsAuthToken);
  this.http
    .post<WindowsLoginRequest>(this.winLoginUrl, loginRequest)
    .subscribe(
      (response: any) => {
        if (response) {
          localStorage.setItem(Constants.jwtToken, response.jwt);
        }
      },
      err => this.logger.logError("Failed to get JWT token", err),
      () => {
        return true;
      }
    );
  } else {
      return false;
  }
}
AGCodes
  • 622
  • 1
  • 8
  • 22

1 Answers1

0

You can create one observable with switchMap

this.http.get(this.authUrl).pipe(
  map(response => response.token),
  switchMap(token => this.http.post<WindowsLoginRequest>(this.winLoginUrl, new WindowsLoginRequest(token)))
)
Adrian Brand
  • 20,384
  • 4
  • 39
  • 60
  • Ok, so if the original token request failed then how will I get the error? Also how do I check that switchmap should only be called if original request was a success. – AGCodes May 21 '19 at 05:27
  • "Also how do I check that switchmap should only be called if original request was a success." It will be. About getting error, add `catchError` before `map` in the pipe. – Roberto Zvjerković May 21 '19 at 06:12
  • you can tap before the map and add an error handler to the original stream and then add a filter after the tap to only allow valid responses through – Adrian Brand May 21 '19 at 06:51