angularthisarrow-functionsintercept

How to refer to component object within intercept/arrow function?


Here's my code:

export class NetworkInterceptor implements HttpInterceptor {
  constructor(private router: Router, private ngZone: NgZone) {}

  intercept(request: HttpRequest<unknown>, next: HttpHandler): Observable<HttpEvent<unknown>> {
    // ...

    return next.handle(request).pipe(
      finalize(() => {
        // ...
      }),
      tap({
        next(res) {},
        error(error) {
          if (error instanceof HttpErrorResponse) {
            if (error.status === 401) {
              this.ngZone.run(() => this.router.navigateByUrl('/account/signin'));
            }
          }
        },
        complete() {},
      })
    );
  }
}

But can't use

this.ngZone.run(() => this.router.navigateByUrl('/account/signin'))

within intercept, since this doesn't refers to component's object.

What's the correct way to do this?


Solution

  • If the intention is to navigate to a route using the router service, on a 401 error, you don't need to use ngZone. ngZone is a service we use when bringing into angular events from the outside of angular's scope/zone.

    What you need is to use catchError in a more simplistic way, you will be set for the win with something like the following:

    export class NetworkInterceptor implements HttpInterceptor {
      constructor(private router: Router) {}
    
      intercept(request: HttpRequest<unknown>, next: HttpHandler): Observable<HttpEvent<unknown>> {
        // ...
        return next.handle(req).pipe(
          catchError((err) => {
            if (err instanceof HttpErrorResponse && err.status === 401) {
              this.router.navigateByUrl('/account/signin');
            }
            return throwError(err);
          })
        );
      }
    }