Angularjs   发布时间:2022-04-20  发布网站:大佬教程  code.js-code.com
大佬教程收集整理的这篇文章主要介绍了Angular 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);
  }
}

请注意,拦截器的作用类似于链,因此您可以设置多个拦截器来执行不同的任务.

大佬总结

以上是大佬教程为你收集整理的Angular 4.3拦截器 – 如何使用?全部内容,希望文章能够帮你解决Angular 4.3拦截器 – 如何使用?所遇到的程序开发问题。

如果觉得大佬教程网站内容还不错,欢迎将大佬教程推荐给程序员好友。

本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。