我已使用授权标头令牌配置HttpInterceptor,并且正在尝试处理HTTP错误。但是未发送授权标头。在添加错误处理程序之前,它工作正常。此外,我已经在AppModule中注册了拦截器。
//我的interceptor.ts
import {Injectable} from '@angular/core';
import {HttpEvent, HttpInterceptor, HttpHandler,
HttpRequest,HttpErrorResponse} from '@angular/common/http';
import {Observable, of} from 'rxjs';
import {catchError} from "rxjs/internal/operators";
import {ToastrService} from "ngx-toastr";
@Injectable()
export class MyInterceptor implements HttpInterceptor {
constructor(private toastService : ToastrService)
{
}
intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
let reqHeader;
if(sessionStorage.getItem('token')!==null || sessionStorage.getItem('token')!==undefined)
reqHeader = req.clone({headers: req.headers.set('Authorization',
sessionStorage.getItem('token'))});
else
reqHeader = req.clone({headers: req.headers.set('Authorization', "123")});
return next.handle(req).pipe(catchError((error, caught) => {
console.log(error);
this.handleAuthError(error);
return of(error);
}) as any);
}
/**
* manage errors
* @param err
* @returns {any}
*/
private handleAuthError(err: HttpErrorResponse): Observable<any> {
//handle your auth error or rethrow
console.log(err);
this.toastService.error("Error Received","Err");
throw err;
}
}
//我的App Module.ts
providers: [{
provide: HTTP_INTERCEPTORS,
useClass: MyInterceptor,
multi: true,
}
答案 0 :(得分:0)
我已经重构了您的代码,您没有以正确的方式抛出错误,请看一下代码。
import { Injectable } from '@angular/core';
import { HttpInterceptor, HttpEvent, HttpHandler, HttpRequest, HttpErrorResponse } from '@angular/common/http';
import { Observable, throwError } from 'rxjs';
import { catchError } from 'rxjs/operators';
@Injectable({
providedIn: 'root'
})
export class IntercepterHttp implements HttpInterceptor {
constructor(
) { }
intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
let reqHeader;
if(sessionStorage.getItem('token')!=null || sessionStorage.getItem('token')!=undefined)
reqHeader = req.clone({headers: req.headers.set('Authorization',
sessionStorage.getItem('token'))});
else
reqHeader = req.clone({headers: req.headers.set('Authorization', "123")});
return next.handle(reqHeader).pipe(
catchError(response => {
if (response instanceof HttpErrorResponse) {
return throwError(response);
}
})
)
}
}