美文网首页
聊一聊Angular的HttpInterceptor与Http请

聊一聊Angular的HttpInterceptor与Http请

作者: 摘片叶子 | 来源:发表于2019-12-20 18:35 被阅读0次

HttpInterceptor

顾名思义 http拦截器。在拦截器里面,我们可以统一对发出的http请求进行拦截,然后就可以开开心心的做一些"见不的人的操作"。

一个简单的栗子

import { HttpInterceptor,HttpRequest,HttpHandler,HttpEvent } from '@angular/common/http';
import { Observable } from 'rxjs';

export class MyHttpInterceptor implements HttpInterceptor {

    constructor() {   
    
    }

    intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
        const newurl = req.url;
        const withCredential = true;
        //更改原来的请求参数,生成一个新的请求
        const clone = req.clone({ url: newurl, withCredentials: withCredential });
        return next.handle(clone)
    }
}

实现自定义拦截器需要实现HttpInterceptor接口的intercept方法

export interface HttpInterceptor {
    intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>>;
}

intercept方法有两个参数

  • req:发出的Http请求对象
  • next:有一个handle方法,它能返回一个Observable对象(ps:能有Observable就意味着我们可以做很多操作了)

上面的代码实现了一个简单的参数,对所有请求都设置了withCredential = true,保证跨域能带上cookie(ps:生产环境千万别这样乱来哦)

HttpInterceptor还可以做很多事情,比如说我们可以利用HttpInterceptor来对每个请求都打上日志

import { Injectable } from '@angular/core';
import { HttpInterceptor, HttpRequest, HttpHandler, HttpResponse } from '@angular/common/http';
import { finalize, tap } from 'rxjs/operators';

@Injectable()
export class LoggingInterceptor implements HttpInterceptor {

  constructor() {}

  intercept(req: HttpRequest<any>, next: HttpHandler) {
    let status: string = '';

    return next.handle(req).pipe(
        tap(
          event => {
            if (event instanceof HttpResponse) {
              status = 'succeeded';
            }
          },
          error => status = 'failed'
        ),
        finalize(() => {
          console.log(status)
        })
    );
  }
}

导入

Angular万物皆模块,所以HttpInterceptor当然是要导入Module里面才能生效鸭

import {HTTP_INTERCEPTORS} from '@angular/common/http';


@NgModule({
  declarations: [
    ***
  ],
  imports: [ 
    ***
  ],
  providers: [
    {
        provide: HTTP_INTERCEPTORS, 
        useClass: MyHttpInterceptor, 
        multi: true 
    },
  ],
  bootstrap: [AppComponent]
})
export class AppModule { }

通过在providers里面声明自定义的拦截器就能使用了,provideuseClassmulti都是Angular依赖注入的参数,这里就不多说了。

multi设置为true的原因是因为HTTP_INTERCEPTORS是多服务TOKEN,也意味着我们可以设置多个HttpInterceptor,比如说:日志拦截器,请求修改拦截器等等。

当多个拦截器的时候,会根据声明顺序来进行执行。

  providers: [
    {
        provide: HTTP_INTERCEPTORS, 
        useClass: A, 
        multi: true 
    },
    {
        provide: HTTP_INTERCEPTORS, 
        useClass: B, 
        multi: true 
    },
    {
        provide: HTTP_INTERCEPTORS, 
        useClass: C, 
        multi: true 
    },
  ],

Request执行的顺序是A->B->C,Response执行的顺序是C->B->A

来一段代码,这里分别是三个拦截器,分别在开始和结束的时候都打上了console语句,然后在AppModule按照相应的顺序进行定义,然后在浏览器查看log打出来的结果

@Injectable()
export class LoggingInterceptor implements HttpInterceptor {

  constructor() {}

  intercept(req: HttpRequest<any>, next: HttpHandler) {
    let status: string = '';
    console.log('this is LoggingInterceptor start')
    return next.handle(req).pipe(
        tap(
          event => {
            console.log('this is LoggingInterceptor end')
          },
          error => status = 'failed'
        ),
        finalize(() => {
          console.log(status)
        })
    );
  }
}


export class CatchInterceptor implements HttpInterceptor{

    constructor(){

    }
    
    intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
        console.log('this is CatchInterceptor start')
        return next.handle(req)
            .pipe(
                tap(
                    event => {
                        console.log('this is CatchInterceptor end')
                    }
                  ),
            )
    }
    
}


export class ApiInterceptor implements HttpInterceptor{

    constructor(){

    }
    
    intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
        console.log('this is ApiInterceptor start')
        const newurl = req.url;
        const withCredential = true;
        const clone = req.clone({ url: newurl, withCredentials: withCredential });
        return next.handle(clone)
        .pipe(
            tap(
                event => {
                    console.log('this is ApiInterceptor end')
                }
              ),
        )
    }
    
}
  providers: [
    {
      provide:HTTP_INTERCEPTORS,
      useClass:ApiInterceptor,
      multi:true,
    },
    {
      provide:HTTP_INTERCEPTORS,
      useClass:LoggingInterceptor,
      multi:true,
    },
    {
      provide:HTTP_INTERCEPTORS,
      useClass:CatchInterceptor,
      multi:true,
    }
  ],
//这是浏览器输出的结果
this is ApiInterceptor start
this is LoggingInterceptor start
this is CatchInterceptor start
this is CatchInterceptor end
this is LoggingInterceptor end
this is ApiInterceptor end

相关文章

  • 聊一聊Angular的HttpInterceptor与Http请

    HttpInterceptor 顾名思义 http拦截器。在拦截器里面,我们可以统一对发出的http请求进行拦截,...

  • 聊一聊Angular的HttpInterceptor与Http请

    上一章讲了HttpInterceptor大概是啥玩意儿的,这一章我们期待的实操来了,听我细细道来 在大多数情况下我...

  • Angular HttpInterceptor拦截器 多情景应用

    HttpInterceptor,是Angular提供用于在全局应用程序级别处理HTTP请求的内置工具,拦截并处理H...

  • SAP Spartacus HTTP请求的错误处理机制

    HttpInterceptor来自Angular标准库,而构造函数里注入的handlers,类型为HttpErro...

  • SAP HANA 通过HTTP请求获取数据信息

    更多内容请关注公众号:SAPtechnical 今天聊一下如何通过HTTP获取系统相关信息,HTTP请求包含许多元...

  • 聊一聊Vector与Stack

    Java Collection系列下面有List,Set,Queue等,而Vector属于List下面的一个实现。...

  • 聊一聊编码与乱码

    认识几种编码方式ASCII计算机发明之后需要使用0和1来表示字符,于是美国人在50年代发明了 ASCII (美国标...

  • 聊一聊PPI与CPI

    PPI是工业生产者出厂价格指数,CPI是居民消费价格指数。由于CPI反映的主要是日常消费品价格的变动水平,人们都对...

  • 聊一聊 喝水与致癌

    以前我们喝井水,有人说不卫生,有各种细菌?于是我们改喝消过毒的自来水。 于是又有人说,消过毒的自来水含有氯等致癌物...

  • 聊一聊癌症与肿瘤

    在我们生活中,癌症就是肿瘤,肿瘤就是癌症。这两个概念基本不分家。但往细的说,这两个概念也是有差别的。 那我们先看一...

网友评论

      本文标题:聊一聊Angular的HttpInterceptor与Http请

      本文链接:https://www.haomeiwen.com/subject/ksiinctx.html