0

I'm trying to create an http interceptor, but I'm getting this error.

Type 'Observable' is not assignable to type 'Observable<HttpEvent>'

import { Injectable } from '@angular/core';
import { HttpRequest, HttpHandler, HttpEvent, HttpInterceptor, HttpErrorResponse } from '@angular/common/http';
import { Observable, throwError } from 'rxjs';
import { catchError, retry } from 'rxjs/operators';

@Injectable()
export class ErrorInterceptor implements HttpInterceptor {
  constructor() { }

  intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
    return next.handle(request).pipe(catchError(err => {
      if (err.status === 401) {
        // auto logout if 401 response returned from api
        //
        location.reload(true);
      }

      const error = err.error.message || err.statusText;
      return throwError(error);
    }))
  }
}

I tried with StackBliz and it compiled it without any issues. Is this a visual studio issue?

https://stackblitz.com/edit/angular-ivy-aczftx?file=src%2Fapp%2Ferror.interceptor.ts

enter image description here

2
  • Should be answered here: stackoverflow.com/questions/51687403/… looks like the same thing. Commented Sep 29, 2020 at 19:40
  • The error is the same @ArthurCam, but the solution cannot be applied in this situation. Commented Sep 29, 2020 at 19:46

1 Answer 1

4

The intercept returning throwError which is not HttpEvent so you could

Replace this

intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> 

With this

intercept(request: HttpRequest<any>, next: HttpHandler): Observable<any> 
Sign up to request clarification or add additional context in comments.

2 Comments

Thank you @KamranKhatti. This works! But I have one more question. I looked at many samples online on how to use HttpInterceptor and everyone is returning Observable<HttpEvent<any>>. Why is this error only happening to me? Did it change in Angular 10?
@jongshin the return type matters you are not returning HttpEvent but only Observable of error, you can find several example of intercept where different return type used we need to use signature of method of what we are returning.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.