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

jong shin
  • 682
  • 1
  • 5
  • 19
  • Should be answered here: https://stackoverflow.com/questions/51687403/type-observablehttpevent-is-not-assignable-to-type-observable looks like the same thing. – Arthur Cam Sep 29 '20 at 19:40
  • The error is the same @ArthurCam, but the solution cannot be applied in this situation. – jong shin Sep 29 '20 at 19:46

1 Answers1

2

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> 
Kamran Khatti
  • 3,754
  • 1
  • 20
  • 31
  • 1
    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>. Why is this error only happening to me? Did it change in Angular 10? – jong shin Sep 29 '20 at 19:49
  • @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. – Kamran Khatti Sep 29 '20 at 19:56