【发布时间】: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