如何在Angular中为HTTP请求服务动态设置Content-Type请求头
实现步骤
- 给
apiCall方法新增可选的contentType入参,支持自定义传入,设置合理默认值避免原有调用逻辑报错 - 基于传入的
contentType构造HttpHeaders请求头实例 - 将构造好的请求头统一注入到所有HTTP请求的配置项中
修改后的完整代码
首先需在文件头部导入HttpHeaders依赖:
import { HttpClient, HttpResponse, HttpHeaders } from '@angular/common/http';
修改后的服务代码:
@Injectable() export class AjaxService { constructor(private _http: HttpClient) {} apiCall( data: any, url: string, method: 'DELETE' | 'GET' | 'HEAD' | 'POST' | 'JSONP' | 'PUT', isRawUrlFormat: boolean = false, // 新增可选的Content-Type参数,默认设为常用的application/json,可根据需求调整默认值 contentType: string = 'application/json' ) { if (isRawUrlFormat === false) { url = environment.apiUrl + '/' + url; } // 统一构造请求配置项 const httpOptions = { observe: 'response' as const, headers: new HttpHeaders({ 'Content-Type': contentType }) }; let request$: Observable<any>; switch (method) { case 'GET': request$ = this._http.get(url, httpOptions); break; case 'POST': request$ = this._http.post(url, data, httpOptions); break; case 'PUT': request$ = this._http.put(url, data, httpOptions); break; default: request$ = this._http.request(method, url, { ...httpOptions, body: data }); } return request$.pipe( map((apiResult: HttpResponse<any>) => { return apiResult.body; }) ); } }
调用示例
- 使用默认
application/json类型无需额外传参,原有调用逻辑完全兼容:
this.ajaxService.apiCall({name: 'test'}, 'user/add', 'POST').subscribe(res => console.log(res))
- 自定义Content-Type为表单编码类型:
this.ajaxService.apiCall(formData, 'file/upload', 'POST', false, 'application/x-www-form-urlencoded').subscribe()
注意:如果是上传文件使用
multipart/form-data类型,不要手动传入该Content-Type,浏览器会自动生成带boundary标识的请求头,手动设置反而会导致boundary缺失报错。
内容的提问来源于stack exchange,提问作者Rahul Kundu
相关产品推荐
相关产品推荐

