angular - 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 方法?那也可以。
解决方案
它是undefined
,因为当你传递函数的引用时,context
丢失了。它context
停止引用InterceptorService
.
您需要context
明确绑定
catchError(this.handleError.bind(this))
或者在箭头函数中调用它,保留它
catchError(err => this.handleError(err))
推荐阅读
- salesforce - sun.security.validator.ValidatorException:PKIX 路径验证失败:java.security.cert.CertPathValidatorException:有效性检查失败
- c# - c# - 使用 linq 的 DataTable 表达式列
- python - 使用 django 验证表单和表单集
- python - NameError:使用'exec'编译python中的宏时未定义名称'load_modules'
- php - PHP 对象被销毁
- python - 如何用每周不同的weekmask计算全年每月的工作日?
- python - 为除中心点处的尖峰外处处为零的数据拟合高斯
- spring-batch - Spring Batch 与 Spring 云数据流
- reactjs - SyntaxError:从(flask)服务器端导出令牌以响应客户端时出现意外的令牌导出
- php - 登录表单 - 错误的在线示例