Angular 4.3拦截器 – 如何使用?
发布时间:2020-12-17 10:17:22 所属栏目:安全 来源:网络整理
导读:我正在构建一个需要授权标头的新应用.通常我使用的东西与 scotch.io article中的方法非常相似.但是我注意到,现在通过新的HttpClientModule在Angular 4生态系统中完全支持HTTP拦截器,我试图找到一些关于如何使用的文档他们. 如果我不正确(从4.3开始)这是注入
我正在构建一个需要授权标头的新应用.通常我使用的东西与
scotch.io article中的方法非常相似.但是我注意到,现在通过新的HttpClientModule在Angular 4生态系统中完全支持HTTP拦截器,我试图找到一些关于如何使用的文档他们.
如果我不正确(从4.3开始)这是注入授权标题的最佳做法,我也愿意接受建议.我的想法是,它是最近添加的一个功能,这意味着可能有充分的理由迁移到“Angular Approved”方法.
这个答案是从CodeWarrior链接的
official documentation借来的.
Angular允许您创建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); } } 请注意,拦截器的作用类似于链,因此您可以设置多个拦截器来执行不同的任务. (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |