2

I want to inject the Angular Router into my HttpInterceptor. Unfortunately, the following error is thrown in the browser console:

TypeError: this.router is undefined

I've added this to my constructor as usual:

constructor (private router: Router) {

}

Additionally, I did the following in my providers array inside the app.module.ts:

{
  provide: HTTP_INTERCEPTORS,
  useClass: MyService,
  multi: true,
  deps: [Router]
}

I want to use the current url inside an if statement in my error handler to provide specific functionalities for different routes:

myErrorHandler(error: HttpErrorResponse) {
   if (this.router.url === 'test') {
     // do something
   } else {
     return throwError(error).pipe(
       // do something
     );
   }
}

What am I doing wrong?

Codehan25
  • 2,704
  • 10
  • 47
  • 94

3 Answers3

3

I found the answer from another relevant topic: Angular 6 Service is undefined after injecting in Interceptor

Basically, the injected constructor variable is not available from the function you pass to the catchError function. You need to access the router directly in your ´intercept method´ like this:

constructor(private router: Router) {
}

intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
    return next.handle(request).pipe(
        catchError((errorResponse: HttpErrorResponse) => {
            // this.router is defined here
        })
    );
}

The problem seems to lie within the catchError. If you print the current scope this in both the intercept and catchError functions you get MyInterceptor and CatchSubscriber respectively. this.router is not available from the CatchSubscriber. You can still use separate functions by adding a private method in your interceptor class:

intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
    return next.handle(request).pipe(
        catchError((errorResponse: HttpErrorResponse) => {
            this.handleError(errorResponse);
        })
    );
}

private handleError(errorResponse: HttpErrorResponse) {
     // this.router is defined here
}

To summarize:

catchError(this.handleError)  // does not work because of different scope

catchError(err => this.handleError(err))  // works because of same scope
Babyburger
  • 1,730
  • 3
  • 19
  • 32
0

Have you done this? Too obvious?

import { Router } from "@angular/router";
Robin Webb
  • 1,355
  • 1
  • 8
  • 15
0

You could try using injector.

constructor(inj: Injector) {
this.router = inj.get(AuthService) }

You should note that it is not possible to import a service that contains httpClientModule to avoid a cyclic dependency.

Seinei
  • 1
  • 1