【问题标题】:Angular - calling service in error interceptorAngular - 在错误拦截器中调用服务
【发布时间】:2018-12-31 13:30:32
【问题描述】:

我的目标是在发生内部服务器错误时添加通用错误警报。下面是我的错误拦截器文件。

import { Injectable } from '@angular/core';
import { HttpInterceptor, HttpErrorResponse} from '@angular/common/http';
import { throwError} from 'rxjs';
import { catchError } from 'rxjs/operators';
import { AlertService } from '../_services/alert.service';

@Injectable({
  providedIn: 'root'
})

export class ErrorInterceptorService implements HttpInterceptor {
  constructor(private alertService: AlertService) { }

  intercept(request, next) {
    return next.handle(request).pipe(catchError(this.handleError));
  }

  handleError(err: HttpErrorResponse) {
    console.log(this.alertService); // returns undefined
    this.alertService.error('Internal Server Error'); // does not work
    return throwError(err);
  }
}

我不是 Angular 专家,这就是为什么我不知道为什么注入的服务返回 undefined 并且我不能在这里使用它。当我从任何组件调用该服务时,它可以工作,但我不想在代码中的每个 HTTP 请求中重复调用此警报。我宁愿把它放在拦截器的一个地方。

【问题讨论】:

标签: angular


【解决方案1】:

替换

this.handleError

error => this.handleError(error)

请注意,由于您想简单地传播原始错误,因此 tap() 运算符更合适:

intercept(request, next) {
  return next.handle(request).pipe(tap(null, error => this.handleError(error)));
}

handleError(err: HttpErrorResponse) {
  console.log(this.alertService); // returns undefined
  this.alertService.error('Internal Server Error');
}

如果您愿意,也可以将函数绑定到 this:

intercept(request, next) {
  return next.handle(request).pipe(tap(null, this.handleError.bind(this)));
}

【讨论】:

  • error => this.handleError(error) - 这解决了我的问题!
  • 这也为我解决了这个问题,但有人可以通过解释为什么提供更多信息吗?
猜你喜欢
  • 2022-01-04
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-12-04
  • 2019-01-08
  • 2016-11-13
  • 2020-11-08
  • 2019-06-03
相关资源
最近更新 更多