我有一个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(我认为(,因为Observable在intercept方法中的管道方式。
在这里,我如何实际引用我的类变量,或者类范围内的任何东西?或者,如何将errorLoggingService传递给handleError方法?那也可以。
它是undefined
,因为当您传递函数的引用时,context
会丢失。其context
停止引用InterceptorService
的实例。
您需要显式绑定context
catchError(this.handleError.bind(this))
或者在箭头函数中调用它,将其保留为
catchError(err => this.handleError(err))