简体   繁体   中英

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'. Type 'void' is not assignable to type '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

import { throwError } from 'rxjs';

and in the end you return the Observable. After console.log() write

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

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

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