jeff.eynon
jeff.eynon

Reputation: 1326

Angular 7 - injected service is always null

I have an Angular 7 app. I created a service that implements HttpInterceptor. Here is the code, minus the imports

@Injectable({
  providedIn: 'root'
})
export class InterceptorService implements HttpInterceptor {

  constructor(private errorLoggingService:ErrorLoggingService) {

  }

  handleError(error: HttpErrorResponse) {    
    this.errorLoggingService.logErrorData(error);
    return throwError(error);
  }

  //configure the interceptor
  intercept(req: HttpRequest<any>, next: HttpHandler):Observable<HttpEvent<any>> {
    return next.handle(req)
      .pipe(
        catchError(this.handleError)
      )
  };
}

The intent here is to catch Http errors (from calling backend services) and log them to the instance of errorLoggingService. The class ErrorLoggingService is defined like this:

@Injectable({
    providedIn: 'root'
})
export class ErrorLoggingService {

    constructor(private httpClient:HttpClient) {

    }

    //logs the error to the nodeJS endpoint
    public logErrorString(error:string)
    {

    }

    public logErrorData(error:any) {

    }

}

My problem is that in the handleError() function, this.errorLoggingService is undefined, because 'this' is referring to the Observable (I think), because of the way the observables are piped in the intercept method.

How do I actually refer to my class variables, or anything at the class scope, here? Or, how do I pass the errorLoggingService to the handleError method? That would be OK, too.

Upvotes: 2

Views: 1697

Answers (1)

Suren Srapyan
Suren Srapyan

Reputation: 68665

It is undefined, cause when you pass reference of the function, the context is lost. Its context stops to refer to the instance of InterceptorService.

You need either to bind the context explicitly

catchError(this.handleError.bind(this))

Or call it in arrow function, preserving it

catchError(err => this.handleError(err))

Upvotes: 3

Related Questions