Angular 10 in catchError() 函数中的 HttpInterceptor 管道错误

HttpInterceptor pipe error in Angular 10 in catchError() function

“(err: any) => void”类型的参数不可分配给“(err: any, caught: Observable) => ObservableInput”类型的参数。 类型 'void' 不可分配给类型 'ObservableInput'.

代码

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


@Injectable()
export class AuthenticationInterceptor implements HttpInterceptor {

    API_SERVER_BASE_URL = "http://localhost:5000/api/v1";
    urlsToNotUse: Array<string>;

    constructor() {
        this.urlsToNotUse = [
            '/user/login',
            .....
        ];
    }


    intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
        const ACCESS_TOKEN = localStorage.getItem("accessToken");
        // if accesstoken is not null
        if (ACCESS_TOKEN && this.isValidRequestForInterceptor(req.url)) {
         .........
         .........
        } else {
            const reqWithoutAuth = req.clone({
                url: this.API_SERVER_BASE_URL + req.url,
            });
            return next.handle(reqWithoutAuth)
                .pipe(
                    tap(evt => { }),
                    catchError(error => {
                        console.log(error);
                     })
                );
        }
    }


    private isValidRequestForInterceptor(requestUrl: string): boolean {
        return !this.urlsToNotUse.includes(requestUrl);
    }

}

确保导入 throwError

import { throwError } from 'rxjs';

最后你 return Observable。 console.log() 后写

return .pipe(
                tap(evt => { }),
                catchError(error => {
                    console.log(error);
                    return throwError(error); // add this line
                 })
            );
import { throwError } from 'rxjs';
import { catchError } from 'rxjs/operators';

另外不要忘记 catchError N.B ~tap~ 已弃用,请改用 map

return [Observable].pipe(
      // We use the map operator to change the data from the  response
      map(value => {
      }),
      catchError(error => {
        return throwError(error)
      }
})