我有一个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‘指的是可观测的(我认为),因为在拦截方法中,可观测到的数据是管道化的。
在这里,我如何实际引用类变量或类范围内的任何内容?或者,如何将errorLoggingService传递给handleError方法?那也没关系。
发布于 2020-03-09 20:35:18
它是undefined,因为当您传递函数的引用时,context就丢失了。它的context停止引用InterceptorService实例。
您需要显式绑定context。
catchError(this.handleError.bind(this))或者用箭头函数调用它,保存它。
catchError(err => this.handleError(err))https://stackoverflow.com/questions/60607703
复制相似问题