其他分享
首页 > 其他分享> > Angular8 拦截器 HttpInterceptor使用

Angular8 拦截器 HttpInterceptor使用

作者:互联网

Angular8 拦截器 HttpInterceptor

一、创建拦截器配置

import { Injectable } from '@angular/core';
import {
    HttpEvent, HttpInterceptor, HttpHandler, HttpRequest, HttpResponse, HttpErrorResponse
} from '@angular/common/http';

import { Observable, of } from 'rxjs';
import { tap } from 'rxjs/operators';
const ignoreToken = ['user', 'evironment'];
@Injectable()
export class TokenInterceptor implements HttpInterceptor {
    intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>>   {
       // console.log(req);
        // 补全地址
        let url = req.url;
        const needToken = ignoreToken.filter(u => url.match(u));
        console.log(needToken); // ['evironment']
        if (url.indexOf('http://') < 0 || url.indexOf('https://') < 0) {
            url = 'http://' + url;
            console.log(url); // http://../../../assets/json/evironment.details.json
        }
        // 设置token的请求头
        // 获取token值(可以从本地缓存里得到)
        const authToken = 'lvxinToken';
        if (authToken) {
            // 服务请求时所有的请求加入token
            const authReq = req.clone({
                headers: req.headers.set('Authorization', 'bearer' + authToken),
                url: req.url
            });
            // 服务器响应结果
            return next.handle(authReq).pipe(tap(event => {
                if (event instanceof HttpResponse) {
                    this.handleData(event);
                }
            }, error => {
                // token过期 服务器错误等处理
            }));
        }
        // 若token不存在,则不对请求进行处理
        return next.handle(req).pipe(tap(event => {
            if (event instanceof HttpResponse) {
                // console.log(event);
                this.handleData(event);
            }
        }, error => {
            // token过期 服务器错误等处理
        }));
    }
    handleData(event: HttpResponse<any> | HttpErrorResponse): Observable<any> {
            // 业务处理:一些通用操作
            switch (event.status) {
                case 200:
                    if (event instanceof HttpResponse) {
                        const body: any = event.body;
                        console.log(event);
                    }
                    break;
                case 401: // 未登录状态码
                    // this.goTo('/login');
                    break;
                case 404:
                case 500:
                    // console.log(event);
                    break;
                default:
                    return of(event);
            }
    }
}

二、挂载拦截器

import { NgModule, APP_INITIALIZER } from '@angular/core';
import { CommonModule, LocationStrategy, HashLocationStrategy } from '@angular/common';

import { CoreRoutingModule } from './core-routing.module';
import { CoreComponent } from './core.component';
import { NavBarComponent } from './components/nav-bar/nav-bar.component';
import { EvironmentService } from './services/evironment.service';
import { HttpClientModule, HTTP_INTERCEPTORS } from '@angular/common/http';
import { TokenInterceptor } from './services/token-interceptor.service';

export function init(evironmentService: EvironmentService) {
  return () => {
    evironmentService.getEvironmentDetail().subscribe();
  };
}
@NgModule({
  declarations: [CoreComponent, NavBarComponent],
  imports: [
    CommonModule,
    CoreRoutingModule,
    HttpClientModule
  ],
  exports: [NavBarComponent],
  providers: [
    EvironmentService,
    {
      provide: LocationStrategy,
      useClass: HashLocationStrategy
    },
    {
      provide: HTTP_INTERCEPTORS,
      useClass: TokenInterceptor,
      multi: true
    },
    {
      provide: APP_INITIALIZER,
      useFactory: init,
      deps: [EvironmentService],
      multi: true
    }
  ]
})
export class CoreModule { }

三、允许创建多个拦截器

import { HTTP_INTERCEPTORS } from '@angular/common/http';
import { NoopInterceptor } from './noop-interceptor';
import { AuthInterceptor } from './authInterceptor';
// 将多个拦截器添加至一个List中,然后一次性挂载
export const httpInterceptorProviders = [
  { provide: HTTP_INTERCEPTORS, useClass: NoopInterceptor, multi: true },
  { provide: HTTP_INTERCEPTORS, useClass: AuthInterceptor, multi: true },
];

import { httpInterceptorProviders } from './httpInterceptorProviders.ts'
@ngModule({
	declarations: [],
	imports:[],
	providers: [ httpInterceptorProviders ]
})

四、效果

在这里插入图片描述

五、学习地址:

拦截器补全请求地址操作
HttpResponse返回的status状态码
拦截器给请求设置token
拦截器官方文档

标签:拦截器,url,req,token,HttpInterceptor,import,event,Angular8
来源: https://blog.csdn.net/lvxinaidou/article/details/106534039