首页 > 解决方案 > Angular 7 - 注入服务始终为空

问题描述

我有一个 Angular 7 应用程序。我创建了一个实现 HttpInterceptor 的服务。这是代码,减去导入

@Injectable({
  providedIn: 'root'
})
export class InterceptorService implements HttpInterceptor {

  constructor(private errorLoggingService:ErrorLoggingService) {

  }

  handleError(error: HttpErrorResponse) {    
    this.errorLoggingService.logErrorData(error);
    return throwError(error);
  }

  //configure the interceptor
  intercept(req: HttpRequest<any>, next: HttpHandler):Observable<HttpEvent<any>> {
    return next.handle(req)
      .pipe(
        catchError(this.handleError)
      )
  };
}

这里的目的是捕获 Http 错误(来自调用后端服务)并将它们记录到 errorLoggingService 的实例中。类 ErrorLoggingService 定义如下:

@Injectable({
    providedIn: 'root'
})
export class ErrorLoggingService {

    constructor(private httpClient:HttpClient) {

    }

    //logs the error to the nodeJS endpoint
    public logErrorString(error:string)
    {

    }

    public logErrorData(error:any) {

    }

}

我的问题是在handleError() 函数中,this.errorLoggingService 是未定义的,因为'this' 指的是Observable(我认为),因为observables 在intercept 方法中的管道方式。

我如何在此处实际引用我的类变量或类范围内的任何内容?或者,如何将 errorLoggingService 传递给 handleError 方法?那也可以。

标签: angulardependency-injectionangular-http-interceptors

解决方案


它是undefined,因为当你传递函数的引用时,context丢失了。它context停止引用InterceptorService.

您需要context明确绑定

catchError(this.handleError.bind(this))

或者在箭头函数中调用它,保留它

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

推荐阅读