首先 新建一个文件夹叫 interceptors,在该文件夹下建一个文件叫param.interceptor.ts,输入ng-http-interceptor创建
import { Injectable } from '@angular/core';
import {
HttpEvent, HttpInterceptor, HttpHandler, HttpRequest
} from '@angular/common/http';
import { environment } from 'src/environments/environment';
@Injectable()
export class ParamInterceptor implements HttpInterceptor {
intercept(req: HttpRequest<any>, next: HttpHandler) {
const modifiedReq = req.clone({
setParams:{ icode:environment.icode }
})
return next.handle(modifiedReq);
}
}
在app.module.ts中添加
providers: [
{
provide:HTTP_INTERCEPTORS,
useClass:ParamInterceptor,
multi:true
}
],
本文介绍如何在Angular项目中创建并使用HTTP拦截器,通过在请求中自动添加参数,实现统一处理请求头信息,简化代码并提高开发效率。
172

被折叠的 条评论
为什么被折叠?



