Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

this.handleError is not a function

trying to figure out why handleError unable to initiate.

our get api call structure

get(relativeUrl: string, _httpOptions?: any) {

    var response = this.http.get(baseUrl + relativeUrl, _httpOptions)
          .pipe(
          catchError(this.HandleRequiredErrorResponse)
        ).toPromise();

            var responsedata = new ResponseData;

            responsedata.statusCode = '200';
            responsedata.response = response;

            return responsedata;
}

This function handles our custom errors if other than our required error we logging it by calling handleError function

HandleRequiredErrorResponse(errorReponse: HttpErrorResponse) {
    var response = new ResponseData;

    if (errorReponse.status == 400) {
      response.statusCode = errorReponse.status.toString();
      response.response = errorReponse.error;
    }
    else if (errorReponse.status == 404) {
      response.statusCode = errorReponse.status.toString();
      response.response = errorReponse.error;
    }
    else {
      console.log(errorReponse)
      let err = this.handleError(errorReponse);//handleError is undefined

      return err;
    }

    return new ErrorObservable(response);
  }

here we logging with some related messages

handleError(error: HttpErrorResponse) {
    if (error.error instanceof ErrorEvent) {
      console.error('An error occurred:', error.error.message);
    } else {
      console.error(
        `Backend returned code ${error.status}, ` +
        `body was: ${error.error}`);
    }
    return new ErrorObservable(
      'Something bad happened; please try again later.');
  }

And my imports are

import { HttpClient, HttpErrorResponse } from '@angular/common/http';
import { Observable } from 'rxjs/Observable';
import { ErrorObservable } from 'rxjs/observable/ErrorObservable';
import { catchError } from 'rxjs/operators';
like image 237
k11k2 Avatar asked Oct 15 '25 16:10

k11k2


1 Answers

It has to do with function scope and closure. Observable operators create a lot of new Observables under the hood, and creating a new object with a constructor also creates a new this context. The catchError parameter doesn't know that this refers to your component when passed in directly.

Just wrap it in a lambda function:

catchError(err => this.HandleRequiredErrorResponse(err))

Lambda/fat arrow methods have a lexical this value, so this will always refer to the object in which the arrow method was called. That relieves a ton of headaches historically associated with JS development.

like image 170
joh04667 Avatar answered Oct 17 '25 06:10

joh04667