聊一聊Angular的HttpInterceptor与Http请求失败的重试(1)

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, next: HttpHandler): Observable> {
        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, next: HttpHandler): Observable>;
}

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, 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, 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, next: HttpHandler): Observable> {
        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, next: HttpHandler): Observable> {
        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请求失败的重试(1))