Angular 10类型'Observable <unknown>'不能分配给类型'Observable <HttpEvent <any >>'

时间:2020-09-29 19:36:28

标签: angular

我正在尝试创建一个HTTP拦截器,但出现此错误。

类型'Observable'不可分配给类型 'Observable '

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);
    }))
  }
}

我尝试过StackBliz,它编译时没有任何问题。这是视觉工作室的问题吗?

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

enter image description here

1 个答案:

答案 0 :(得分:1)

intercept返回的throwError不是HttpEvent,所以您可以

替换

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

与此

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