简体   繁体   English

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

[英]HttpInterceptor pipe error in Angular 10 in catchError() function

Argument of type '(error: any) => void' is not assignable to parameter of type '(err: any, caught: Observable<HttpEvent>) => ObservableInput'. “(error: any) => void”类型的参数不可分配给“(err: any,catch: Observable<HttpEvent>) => ObservableInput”类型的参数。 Type 'void' is not assignable to type 'ObservableInput'. “void”类型不能分配给“ObservableInput”类型。

在此处输入图片说明

Code代码

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

}

Make sure you import throwError确保你导入 throwError

import { throwError } from 'rxjs';

and in the end you return the Observable.最后你返回 Observable。 After console.log() write在 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';

Also dont forget the catchError NB ~tap~ has been depricated, use map insted也不要忘记 catchError NB ~tap~ 已被弃用,使用map insted

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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