Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/angular/28.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Angular 角度7-注入服务始终为空_Angular_Dependency Injection_Angular Http Interceptors - Fatal编程技术网

Angular 角度7-注入服务始终为空

Angular 角度7-注入服务始终为空,angular,dependency-injection,angular-http-interceptors,Angular,Dependency Injection,Angular Http Interceptors,我有一个角度7应用程序。我创建了一个实现HttpInterceptor的服务。这是代码,减去导入 @Injectable({ providedIn: 'root' }) export class InterceptorService implements HttpInterceptor { constructor(private errorLoggingService:ErrorLoggingService) { } handleError(error: HttpError

我有一个角度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)
      )
  };
}
我的问题是,在handleError()函数中,this.errorLoggingService是未定义的,因为“this”指的是可观察对象(我认为),因为在intercept方法中可观察对象是通过管道传输的


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

它是
未定义的
,因为当您传递函数的引用时,
上下文
丢失。它的
上下文
停止引用
拦截器服务
的实例

您需要显式地绑定
上下文

catchError(this.handleError.bind(this))
或者在arrow函数中调用它,保留它

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

如果你只是把它变成一个箭头函数,它应该可以工作:
catchError((error:error)=>{this.handleError(error)}
,除非我遗漏了什么。目前有一个类似的方案,使用一个全局toastService,不存在任何问题。
catchError(err => this.handleError(err))