mike927
mike927

Reputation: 774

Angular - calling service in error interceptor

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.

Upvotes: 0

Views: 1066

Answers (1)

JB Nizet
JB Nizet

Reputation: 691635

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

Upvotes: 1

Related Questions