Search code examples
angularangular-http-interceptors

Angular 9 - HttpInterceptor - Cannot read property length of null


I use Angular 9 and HttpInterceptor like this:

export class AppHttpInterceptor implements HttpInterceptor {

    intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
      ...
      return next.handle(authReq).catch((error, caught) => {
        if(error.status === 403) {
            this.router.navigate(['/login']); 
        } else if(error.status === 400) {
            console.log('Error status 400');
        }
        return Observable.throw(error);
    }) as any;

and I get the following Error when I load the application initially:

ERROR TypeError: Cannot read property 'length' of null
at http.js:168
at Array.forEach (<anonymous>)
at HttpHeaders.lazyInit (http.js:156)
at HttpHeaders.init (http.js:277)
at HttpHeaders.forEach (http.js:379)
at Observable._subscribe (http.js:2376)
at Observable._trySubscribe (Observable.js:42)
at Observable.subscribe (Observable.js:28)
at CatchOperator.call (catchError.js:16)
at Observable.subscribe (Observable.js:23)

Does anyony know why and how to prevent this error?


Solution

  • Try like this, because you can't get property status from the error response object it will be error.error.status

    intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
          ...
          return next.handle(authReq).catch((error, caught) => {
            if(error.error.status === 403) {
                this.router.navigate(['/login']); 
            } else if(error.error.status === 400) { 
                console.log('Error status 400');
            }
            return Observable.throw(error);
        }) as any;