23

How do I do the following with lettable operators and pipe?

    this.httpClient
      .get(url)
      .map((res: any) => {
        const events = res.eventList;
        return events.map(e => new EventLogModel(e));
      })
      .catch(this.handleError);

I've tried this, but I can't get catchError to work: catchError does not exist on type Observable<any>:

    this.httpClient
      .get(url)
      .pipe(
        map((res: any) => {
          const events = res.eventList;
          return events.map(e => new EventLogModel(e));
        })
      )
      .catchError(this.handleError);

Also, I assume catch and catchError are the same, correct? I'm importing it like so:

import { map, catchError } from 'rxjs/operators';

but I wasn't sure if this was the correct operator to use.

Nxt3
  • 1,970
  • 4
  • 30
  • 52

1 Answers1

34

Your assumption is correct, the lettable operator catchError is the same as catch.

As for the placement of catchError, it should not have prefix . and should be placed within pipe:

this.httpClient
  .get(url)
  .pipe(
    map((res: any) => {
      const events = res.eventList;
      return events.map(e => new EventLogModel(e));
    }),
    catchError(this.handleError);
  )
AT82
  • 71,416
  • 24
  • 140
  • 167
  • For future readers, here is a crappy no frills handleError routine. – granadaCoder Jan 25 '19 at 15:12
  • //import { HttpClient, HttpHeaders, HttpErrorResponse } from '@angular/common/http'; private handleError(error: HttpErrorResponse) { if (error.error instanceof ErrorEvent) { // A client-side or network error occurred. Handle it accordingly. //alert('ErrorEvent ' + error.error.message); console.error('An error occurred:', error.error.message); } else { // The backend returned an unsuccessful response code. // The response body may contain clues as to what went wrong, – granadaCoder Jan 25 '19 at 15:12
  • //alert('Else ' + error.status + ':::' + error.error); console.error( `Backend returned code ${error.status}, ` + `body was: ${error.error}`); } // return an observable with a user-facing error message return throwError( 'Something bad happened; please try again later.'); }; – granadaCoder Jan 25 '19 at 15:12
  • 1
    How do I import catchError ? – Dipendu Paul Mar 16 '21 at 11:39
  • 1
    @DipenduPaul import {catchError} from 'rxjs/operators'; – Brandon May 23 '21 at 06:29