我正在尝试创建一个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
答案 0 :(得分:1)
intercept
返回的throwError
不是HttpEvent
,所以您可以
替换
intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>>
与此
intercept(request: HttpRequest<any>, next: HttpHandler): Observable<any>