0

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.

mike927
  • 682
  • 1
  • 8
  • 25
  • Possible duplicate of [How to access the correct \`this\` inside a callback?](https://stackoverflow.com/questions/20279484/how-to-access-the-correct-this-inside-a-callback) – ConnorsFan Dec 31 '18 at 14:13

1 Answers1

1

Replace

this.handleError

by

error => this.handleError(error)

Note that since you want to simply propagate the original error, the tap() operator is more appropriate:

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');
}

You can also bind the function to this if you prefer:

intercept(request, next) {
  return next.handle(request).pipe(tap(null, this.handleError.bind(this)));
}
JB Nizet
  • 678,734
  • 91
  • 1,224
  • 1,255