Angular 7 - 注入的服务始终为空
Angular 7 - injected service is always null
我有一个 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 的实例中。 class 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 在拦截方法。
我如何在此处实际引用我的 class 变量或 class 范围内的任何内容?或者,如何将 errorLoggingService 传递给 handleError 方法?那也可以。
它是undefined
,因为当你传递函数的引用时,context
丢失了。它的 context
停止引用 InterceptorService
.
的实例
您需要显式绑定 context
catchError(this.handleError.bind(this))
或者在箭头函数中调用它,保留它
catchError(err => this.handleError(err))
我有一个 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 的实例中。 class 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 在拦截方法。
我如何在此处实际引用我的 class 变量或 class 范围内的任何内容?或者,如何将 errorLoggingService 传递给 handleError 方法?那也可以。
它是undefined
,因为当你传递函数的引用时,context
丢失了。它的 context
停止引用 InterceptorService
.
您需要显式绑定 context
catchError(this.handleError.bind(this))
或者在箭头函数中调用它,保留它
catchError(err => this.handleError(err))