大佬教程收集整理的这篇文章主要介绍了Angular 4.3拦截器 – 如何使用?,大佬教程大佬觉得挺不错的,现在分享给大家,也给大家做个参考。
如果我不正确(从4.3开始)这是注入授权标题的最佳做法,我也愿意接受建议.我的想法是,它是最近添加的一个功能,这意味着可能有充分的理由迁移到“Angular Approved”方法.
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); } }
以上是大佬教程为你收集整理的Angular 4.3拦截器 – 如何使用?全部内容,希望文章能够帮你解决Angular 4.3拦截器 – 如何使用?所遇到的程序开发问题。
如果觉得大佬教程网站内容还不错,欢迎将大佬教程推荐给程序员好友。
本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。