complicated pipe chain with the HttpClient in Angular with RxJS

Viewed 334

I dont have a lot experience in RxJS and I want to do the following thing with a RxJS pipe in my Angular service.

I tried with the iif function but I simply have not enough experience in it.

Angular Version is: Angular 9
RxJS Version: 6.5.5

check response from GET request true via HttpClient
.... true -> check if can access website via HttpClient
................ true -> set this.isOnline = true
............................ get a response from another url via HttpClient
............................ true -> set this.result = responseFromUrl
........................................ end pipe
............................ false -> throwError("cant get result")
................ false -> set this.isOnline = false
............................. end pipe
.... false -> end pipe

1 Answers

Try the following

import { EMPTY } from 'rxjs';
import { concatMap } from 'rxjs/operators';

http.get(api).pipe(
  concatMap(reponseOne => {
    return http.get(accessWebsiteApi).pipe(
      concatMap(responseTwo => {
        this.isOnline = true;
        return http.get(anotherUrl);
      }),
      catchError(errorTwo => {
        this.isOnline = false;
        return EMPTY;
      })
    );
  })
).subscribe(
  responseFromUrl => {
    this.result = responseFromUrl;
  },
  error => {
    console.error("cant get result");
  }
);
Related