简体   繁体   中英

Angular 10 Type 'Observable<unknown>' is not assignable to type 'Observable<HttpEvent<any>>'

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

在此处输入图片说明

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> 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM