我正在构建一个需要授权标头的新应用.通常我使用的东西与
scotch.io article中的方法非常相似.但是我注意到,现在通过新的HttpClientModule在Angular 4生态系统中完全支持HTTP拦截器,我试图找到一些关于如何使用的文档他们.
如果我不正确(从4.3开始)这是注入授权标题的最佳做法,我也愿意接受建议.我的想法是,它是最近添加的一个功能,这意味着可能有充分的理由迁移到“Angular Approved”方法.
这个答案是从CodeWarrior链接的
official documentation借来的.
原文链接:https://www.f2er.com/angularjs/240410.htmlAngular允许您创建HttpInterceptor:
import {Injectable} from '@angular/core'; import {HttpEvent,HttpInterceptor,HttpHandler,HttpRequest} from '@angular/common/http'; @Injectable() export class NoopInterceptor implements HttpInterceptor { intercept(req: HttpRequest<any>,next: HttpHandler): Observable<HttpEvent<any>> { return next.handle(req); } }
您可以将其集成到您的应用中,如下所示:
import {NgModule} from '@angular/core'; import {HTTP_INTERCEPTORS} from '@angular/common/http'; @NgModule({ providers: [{ provide: HTTP_INTERCEPTORS,useClass: NoopInterceptor,multi: true,}],}) export class AppModule {}
要添加授权标头,您可以使用更改的标头克隆请求:
import {Injectable} from '@angular/core'; import {HttpEvent,HttpRequest} from '@angular/common/http'; @Injectable() export class AuthInterceptor implements HttpInterceptor { constructor(private auth: AuthService) {} intercept(req: HttpRequest<any>,next: HttpHandler): Observable<HttpEvent<any>> { // Get the auth header from the service. const authHeader = this.auth.getAuthorizationHeader(); // Clone the request to add the new header. const authReq = req.clone({headers: req.headers.set('Authorization',authHeader)}); // Pass on the cloned request instead of the original request. return next.handle(authReq); } }