Rxjs 6: using catchError() gives You provided '

2019-07-11 06:49发布

问题:

I'm using the new syntax to comply with RxJS 6 pipe(). Also using Angular 6. I have a service that handles http requests, and it pipes map and catchError to display a toast in case of connection error. Nevertheless, If I add catchError I get in console You provided 'undefined' where a stream was expected. You can provide an Observable, Promise, Array, or Iterable.

  getDataHttpRequest(url, returnType) {
    return this.http.get(url, this.getRequestOptions())
    .pipe(
      map((response) => {

        if(response){

        if (returnType === 'object') {
          return response[0] == undefined ? response : response[0];
        } else {
          return response;
        }

      }
      }),
      catchError((error):any => {

      if(error instanceof HttpErrorResponse && error.status === 0){
        //no connection error(either user has no connection or the server is down)
       this.toastr.error('Chequee su conexión e intente de nuevo en unos momentos. Contáctenos para reportar el problema a <a href="mailto:dev@info.com">dev@info.com</a>',"Error de Conexión",{tapToDismiss:true, disableTimeOut: true});
      }
       throwError(`Connection Error: ${error}`);
      })


    );

  }

If I remove the catchError function the errors disappear in console, so that is the breaking piece of code. Any ideas on what could be wrong?

回答1:

The callback for catchError needs to return an Observable (it might throw an exception that will be converted to error as well I think).

catchError((error):any => {
  if (whatever) {
    ...
    return empty(); // just complete
  }
  return throwError(`Connection Error: ${error}`); // return another `error`
});