You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Angular 15中如何向DELETE API请求体传递ID数组?

解决Angular 15 DELETE请求传递ID数组的媒体类型错误问题

你的代码报错原因是Angular的HttpClient.delete()方法第二个参数并非直接传请求体,而是需要传入配置选项对象,且未指定正确的请求头导致后端无法识别请求体格式。

修正步骤:

  • 将ID数组放入配置选项的body属性中
  • 添加Content-Type: application/json请求头,明确告知后端请求体格式

修正后的代码:

import { HttpClient, HttpHeaders } from '@angular/common/http';
// ...

deleteProduct(productId: number): Observable<any> {
  // 构造要传递的ID数组(单个ID转为数组,支持批量删除可直接传数组参数)
  const idArray = [productId];
  
  // 配置请求选项:指定请求体和请求头
  const options = {
    headers: new HttpHeaders({
      'Content-Type': 'application/json'
    }),
    body: idArray
  };

  return this.http
    .delete(`${this.baseUrl}api/Product/deleteproduct`, options)
    .pipe(map(data => data));
}

扩展:支持批量删除的版本

如果需要一次删除多个ID,可修改方法参数为数组:

deleteProducts(productIds: number[]): Observable<any> {
  const options = {
    headers: new HttpHeaders({
      'Content-Type': 'application/json'
    }),
    body: productIds
  };

  return this.http
    .delete(`${this.baseUrl}api/Product/deleteproduct`, options)
    .pipe(map(data => data));
}

这样后端就能正确接收到JSON格式的ID数组,解决媒体类型不支持的错误。

内容的提问来源于stack exchange,提问作者HarrY

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.14 20:03:14