Search code examples
angulartypescriptrxjsobservable

How can I return an error in an Observable function with multiple cases based on the page the user is on in an Angular application?


I have a getElementList() function: Observable<Element[]>, I'd like to handle three cases in this function depending on the page the user is on ( 2 cases for 2 different pages and 1 error case) but I can't figure out how to return an error for an Observable<Element[]>.

  getElementList() : Observable<Element[]>{
    const isOnClubsPage: boolean = this.router.url.endsWith('/Clubs');
    const isOnPartenairePage: boolean = this.router.url.endsWith('/Partenaires');
    if (isOnClubsPage) {
      return this.http.get<Element[]>('api/Clubs').pipe(
        tap((clubList) => this.log(clubList)),
        catchError((error) => this.handleError(error, []))
      );
    }
    else if(isOnPartenairePage){
      return this.http.get<Element[]>('api/Partenaires').pipe(
        tap((clubList) => this.log(clubList)),
        catchError((error) => this.handleError(error, []))
      );
    }else{
      return error??
    }
  }

I'd like to throw an error in the last if but I can't figure out how to do it.


Solution

  • To solve my problem, i return that in the else case :

    else{
      return throwError(() => new Error('erreur'));
    }