在services文件夹下新建一个文件夹http-interceptors,在其中创建一个通常状态下的拦截器文件,下图代码拦截器对请求信息不做任何处理
// common.interceptor.ts
import { Injectable } from '@angular/core';
import { HttpInterceptor, HttpRequest, HttpHandler, HttpEvent } from '@angular/common/http';
import { Observable } from 'rxjs';
@Injectable()
export class CommonInterceptor implements HttpInterceptor {
intercept(req: HttpRequest<any>, next: HttpHandler ): Observable<HttpEvent<any>> {
return next.handle(req);
}
}
需要处理请求信息需要使用do someing替换req,例如给所有请求添加withCredentials跨域可能
// common.interceptor.ts
import { Injectable } from '@angular/core';
import { HttpInterceptor, HttpRequest, HttpHandler, HttpEvent } from '@angular/common/http';
import { Observable } from 'rxjs';
@Injectable()
export class CommonInterceptor implements HttpInterceptor {
intercept(req: HttpRequest<any>, next: HttpHandler ): Observable<HttpEvent<any>> {
return next.handle(req.clone({
withCredentials: true
}));
}
}
如果设置的拦截器为一个或者多个,在文件夹下新建index文件,将拦截器的处理作为数组成员传入
// index.ts
import { CommonInterceptor } from './common.interceptor';
import { HTTP_INTERCEPTORS } from '@angular/common/http';
export const httpInterceptorProvides = [
{ provide: HTTP_INTERCEPTORS, useClass: CommonInterceptor, multi: true},
{ provide: HTTP_INTERCEPTORS, useClass: CommonInterceptor1, multi: true},
{ provide: HTTP_INTERCEPTORS, useClass: CommonInterceptor2, multi: true}
];
之后将httpInterceptorProvides导入servicesModule的providers中就可以正常使用了
import { httpInterceptorProvides } from './http-interceptors/index';
import { NgModule, InjectionToken, PLATFORM_ID } from '@angular/core';
import { isPlatformBrowser } from '@angular/common';
export const API_CONFIG = new InjectionToken('ApiConfigToken');
export const WINDOW = new InjectionToken('WindowToken');
@NgModule({
declarations: [],
imports: [],
providers: [
{
provide: API_CONFIG, useValue: 'http://localhost:3000/'
},
{
provide: WINDOW,
useFactory(platfromId: object): Window | object {
return isPlatformBrowser(platfromId) ? window : {};
},
deps: [PLATFORM_ID]
},
httpInterceptorProvides
],
})
export class ServicesModule { }
仅作笔记,感谢指正