this.handleError不是函数

时间:2018-08-28 14:46:40

标签: angular rxjs observable

试图弄清为什么handleError无法启动。

我们的api调用结构

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;
}

如果我们需要通过调用handleError函数对其进行记录,则该函数将处理我们的自定义错误

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);
  }

我们在这里记录一些相关消息

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.');
  }

我的进口货是

import { HttpClient, HttpErrorResponse } from '@angular/common/http';
import { Observable } from 'rxjs/Observable';
import { ErrorObservable } from 'rxjs/observable/ErrorObservable';
import { catchError } from 'rxjs/operators';

2 个答案:

答案 0 :(得分:0)

执行此操作:

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

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

        var responsedata = new ResponseData;

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

        return responsedata;
}

答案 1 :(得分:0)

它与功能范围和闭包有关。可观察运算符在幕后创建了许多新的可观察变量,并且使用构造函数创建新对象也创建了新的this上下文。 catchError参数不知道this是直接传递给您的组件的。

只需将其包装在lambda函数中即可:

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

Lambda / fat箭头方法没有this值,可以缓解历史上与JS开发相关的头痛。