2

I am currently learning Angular 6 and RXJS through using the HTTPClient.

The documentation https://angular.io/guide/http states that you can catch an error within the this.http.get method using pipe then tap like the example below lifted from the official docs.

getTextFile(filename: string) {
    // The Observable returned by get() is of type Observable<string>
    // because a text response was specified.
    // There's no need to pass a <string> type parameter to get().
    return this.http.get(filename, {responseType: 'text'})
    .pipe(
        tap( // Log the result or error
        data => this.log(filename, data),
        error => this.logError(filename, error)
        )
    );
}

I am trying to replicate this within my method like so

getLeads() : Observable<Lead[]> {
  return this.http.get<Lead[]>('http://localhost:3000/leads').pipe(
      tap (
        error => console.log('error')
      )
  );
}

But it's not catching the error within tap(), however when using catchError like the below it does work.

getLeads() : Observable<Lead[]> {
  return this.http.get<Lead[]>('http://localhost:3000/leads').pipe(
      catchError(this.errorHandlerService.handleError('Could not get Leads', [])),
  );
}

Is there a reason why the below is not working?

tap (
  error => console.log('error')
)
2
  • 1
    You're only passing the first callback to tap, which gets the non-error result. That's not the same as the example. Commented Jul 27, 2018 at 15:21
  • Thanks @jonrsharpe. Commented Jul 27, 2018 at 15:26

1 Answer 1

7

The name of the callbacks for these methods are irrelevant.

tap (
   error => console.log('error')
)

In this case, 'error' is actually a 'success' callback. If you want to handle an error, you need the second parameter of the tap operator.

tap (
   success => console.log('success'),
   error => console.log('error')
)
Sign up to request clarification or add additional context in comments.

1 Comment

Neither of those callbacks has a name, do you mean the names of the parameters?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.