使用Angular 6,我在过去两天尝试了许多不同的方法,最近发布了这篇文章:
https://stackoverflow.com/a/47401544.但是,标题仍然没有按请求设置.
import {Inject,Injectable} from '@angular/core'; import { HttpEvent,HttpInterceptor,HttpHandler,HttpRequest,HttpErrorResponse,} from '@angular/common/http'; import { Observable } from 'rxjs/Observable'; @Injectable() export class AuthTokenInterceptor implements HttpInterceptor { constructor() {} intercept(req: HttpRequest<any>,next: HttpHandler): Observable<HttpEvent<any>> { return next.handle(req).do((event: HttpEvent<any>) => { if (localStorage.getItem('id_token') != null) { // Clone the request to add the new header. const request = req.clone({ setHeaders: { 'Content-Type' : 'application/json; charset=utf-8','Accept' : 'application/json','Authorization': `Bearer ${localStorage.getItem('id_token')}` } }); return next.handle(request); } },(err: any) => { if (err instanceof HttpErrorResponse) { if (err.status === 401) { console.log('redirect auth interceptor') // do a redirect } } }); } }
如果我注销请求,request.headers.lazyUpdate数组正在使用3个项目进行更新,但我没有在请求拦截中看到Authorization标头.
request.headers.lazyUpdate:
{name: "Content-Type",value: "application/json; charset=utf-8",op: "s"} {name: "Accept",value: "application/json",op: "s"} {name: "Authorization",value: "Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ2Mzh9.tLTmPK46NhXSuqoCfZKgZcrQWzlNqLMI71-G0iy3bi8",op: "s"}
(request.headers.headers是空的—这可能是问题吗?)
app.module.ts:
providers: [ {provide: HTTP_INTERCEPTORS,useClass: AuthTokenInterceptor,multi: true},],
是什么导致我认为这是一个拦截器问题,如果我手动将标头添加到请求,我没有得到401并且请求返回正确的数据和200:
return this.http.get(environment.API_URL + 'list/supervise/' + encodeURIComponent(id),{headers: new HttpHeaders().set('Authorization',`Bearer ${localStorage.getItem('id_token')}`)}).pipe( map((res: any) => res.data) );
有什么我可以忽略的吗?谢谢.
编辑:
正如我在下面的评论中提到的那样,我将返回next.handle两次.这是我最终得到的解决方案:
import {Injectable} from '@angular/core'; import { HttpEvent,HttpRequest } from '@angular/common/http'; import { Observable } from 'rxjs'; @Injectable() export class AuthTokenInterceptor implements HttpInterceptor { constructor() {} intercept(req: HttpRequest<any>,next: HttpHandler): Observable<HttpEvent<any>> { const token = localStorage.getItem('id_token'); req = req.clone({ setHeaders: { 'Authorization': `Bearer ${token}` },}); return next.handle(req); } }
解决方法
您可以尝试更简单的版本.(就像您的参考链接一样)
intercept(req: HttpRequest<any>,next: HttpHandler): Observable<HttpEvent<any>> { const jwt = localStorage.getItem('id_token'); if (!!jwt) { req = req.clone({ setHeaders: { Authorization: `Bearer ${jwt}` } }); } return next.handle(req); }
您不必在此处理错误
因为在这里(在你的上下文中)intercepter的意思是克隆(这意味着每当我们接受请求时,我们克隆它,然后做我们想做的任何事情并将其发送出去).
我们可以添加更多标题更多数据
它将被送走,然后最终从Api返回
并将句柄问题留给调用httpRequest的服务(例如:then,catch,pipe,…).
再次,您在app.module.ts中声明了这一点,这意味着您的应用程序中的所有请求api都将被拦截,如果我想处理具有错误消息Nothing here的特定请求,如果您执行一些复杂的逻辑,该怎么办?,它可能会影响所有请求.
关于你上面的代码,我没有尝试过,但我认为当你嵌套这样的东西时,他们可能会发生错误,你应该把它们放在断点上并尝试调试发生的事情.