新建?p>
菇仄鳎柚?XMLHttpRequest:withCredentials 属性
1. 新建文件夹 http-interceptors
该文件夹下可有多个不同用途的拦截器
2. 新建拦截器 common.interceptor.ts
import { HttpEvent, HttpHandler, HttpInterceptor, HttpRequest } from "@angular/common/http"; import { Injectable } from "@angular/core"; 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 })); }
3. 用一个数组汇总起来,统一引入: index.ts (后续需要添加拦截器,只需加入到该数组即可)
import { HTTP_INTERCEPTORS } from "@angular/common/http"; import { CommonInterceptor } from "./common.interceptor"; export const httpInterceptorProvides = [ { provide: HTTP_INTERCEPTORS, useClass: CommonInterceptor, //指定使用哪个拦截器 multi: true //表示可设置多个拦截器 } ]
4. 引入拦截器使用: service.module.ts
import { isPlatformBrowser } from '@angular/common'; import { InjectionToken, NgModule, PLATFORM_ID } from '@angular/core'; import { httpInterceptorProvides } from './http-interceptors'; 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(platformId: Object): Window | Object { return isPlatformBrowser(platformId) ? window : {}; }, deps: [PLATFORM_ID] }, httpInterceptorProvides ] }) export class ServicesModule { }