[英]HttpInterceptor pipe error in Angular 10 in catchError() function
“(error: any) => void”類型的參數不可分配給“(err: any,catch: Observable<HttpEvent>) => 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';
最后你返回 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 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.