My goal is to add generic error alert when internal server error happens. Below is my error interceptor file.
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);
}
}
I am not expert to Angular that's why I don't know why injected service returns undefined and I can not use it here. When I call that service from any component then it works but I don't want to repeat calling this alert in every HTTP request in code. I would rather prefer put it in one place in interceptor.