簡體   English   中英

Angular2 中 Http.DELETE 請求的正文

[英]Body of Http.DELETE request in Angular2

我正在嘗試從 Angular 2 前端與有點 RESTful API 交談。

要從集合中刪除某些項目,除了刪除的唯一 ID(可以附加到 url)之外,我還需要發送一些其他數據,即身份驗證令牌、一些集合信息和一些輔助數據。

我發現這樣做最直接的方法是將身份驗證令牌放在請求標頭中,並將其他數據放在正文中。

但是,Angular 2 的 Http 模塊並不完全同意帶有主體的 DELETE 請求,並試圖發出這個請求

let headers= new Headers();
headers.append('access-token', token);

let body= JSON.stringify({
    target: targetId,
    subset: "fruits",
    reason: "rotten"
});

let options= new RequestOptions({headers:headers});
this.http.delete('http://testAPI:3000/stuff', body,options).subscribe((ok)=>{console.log(ok)}); <------line 67

給出這個錯誤

app/services/test.service.ts(67,4): error TS2346: Supplied parameters do not match any signature of call target.

現在,我在語法方面做錯了嗎? 我很確定每個 RFC 都支持 DELETE 正文

有沒有更好的方法來發送這些數據?

還是我應該將其轉儲到標題中並收工?

對此難題的任何見解將不勝感激

http.delete(url, options)確實接受正文。 您只需將其放在選項對象中。

http.delete('/api/something', new RequestOptions({
   headers: headers,
   body: anyObject
}))

參考選項接口: https ://angular.io/api/http/RequestOptions

更新

上面的代碼片段僅適用於 Angular 2.x、4.x 和 5.x。

對於 6.x 以后的版本,Angular 提供了 15 種不同的重載。 在此處檢查所有重載: https ://angular.io/api/common/http/HttpClient#delete

使用示例:

const options = {
  headers: new HttpHeaders({
    'Content-Type': 'application/json',
  }),
  body: {
    id: 1,
    name: 'test',
  },
};

this.httpClient
  .delete('http://localhost:8080/something', options)
  .subscribe((s) => {
    console.log(s);
  });

如果您使用 Angular 6,我們可以將 body 放入http.request方法中。

來自github的參考

你可以試試這個,對我來說它有效。

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

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.scss'],
})
export class AppComponent {

  constructor(
    private http: HttpClient
  ) {
    http.request('delete', url, {body: body}).subscribe();
  }
}

在 Angular 5 中,我必須使用request方法而不是delete來發送正文。 delete方法的文檔不包括body ,但它包含在 request 方法中。

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

this.http.request('DELETE', url, {
  headers: new HttpHeaders({
    'Content-Type': 'application/json',
  }),
  body: { foo: bar }
});

實際上,您可以使用request方法欺騙Angular2 HTTP發送帶有DELETEbody 這是如何:

let body = {
    target: targetId,
    subset: "fruits",
    reason: "rotten"
};

let options = new RequestOptionsArgs({ 
    body: body,
    method: RequestMethod.Delete
  });

this.http.request('http://testAPI:3000/stuff', options)
    .subscribe((ok)=>{console.log(ok)});

請注意,您必須在RequestOptionsArgs中設置請求方法,而不是在http.request的替代第一個參數Request中。 由於某種原因,這會產生與使用http.delete相同的結果

我希望這會有所幫助,而且我不會遲到。 我認為有角的人在這里不允許通過刪除傳遞身體是錯誤的,即使不鼓勵這樣做。

下面是帶有新 HttpClient 的 Angular 4/5 的相關代碼示例。

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

public removeItem(item) {
    let options = {
      headers: new HttpHeaders({
        'Content-Type': 'application/json',
      }),
      body: item,
    };

    return this._http
      .delete('/api/menu-items', options)
      .map((response: Response) => response)
      .toPromise()
      .catch(this.handleError);
  }

對於 Angular 10,您還可以使用通用請求格式和 DELETE 方法:

http.request('DELETE',  path, {
            body:body,
            headers: httpHeaders,
            params: ((params != null) ? params : new HttpParams())
        })

以下是 Angular 6 的示例

deleteAccount(email) {
            const header: HttpHeaders = new HttpHeaders()
                .append('Content-Type', 'application/json; charset=UTF-8')
                .append('Authorization', 'Bearer ' + sessionStorage.getItem('accessToken'));
            const httpOptions = {
                headers: header,
                body: { Email: email }
            };
            return this.http.delete<any>(AppSettings.API_ENDPOINT + '/api/Account/DeleteAccount', httpOptions);
        }

REST 不會阻止包含 DELETE 請求的正文,但最好使用查詢字符串,因為它是最標准化的(除非您需要加密數據)

我通過執行以下操作使其與 angular 2 一起工作:

let options:any = {}
option.header = new Headers({
    'header_name':'value'
});

options.search = new URLSearchParams();
options.search.set("query_string_key", "query_string_value");

this.http.delete("/your/url", options).subscribe(...)

以下是 Angular 2/4/5 項目的相關代碼示例:

let headers = new Headers({
  'Content-Type': 'application/json'
});

let options = new RequestOptions({
  headers: headers,
  body: {
    id: 123
  }
});

return this.http.delete("http//delete.example.com/delete", options)
  .map((response: Response) => {
    return response.json()
  })
  .catch(err => {
    return err;
  });

請注意, body是通過RequestOptions傳遞的

在 Angular Http 7 中,DELETE 方法接受作為第二個參數options對象,您可以在其中提供請求參數作為params對象以及headers對象。 這與 Angular6 不同。

參見示例:

this.httpClient.delete('https://api-url', {
    headers: {},
    params: {
        'param1': paramValue1,
        'param2': paramValue2
    }
});
deleteInsurance(insuranceId: any) {
    const insuranceData = {
      id : insuranceId
    }
    var reqHeader = new HttpHeaders({
            "Content-Type": "application/json",
        });
        const httpOptions = {
            headers: reqHeader,
            body: insuranceData,
        };
    return this.http.delete<any>(this.url + "users/insurance", httpOptions);
    }

在 Angular 13 中,這對我很有效:

const options = {
   headers: this._headers,
   body: JSON.stringify(user)
};

return this._http.delete<DeleteVirtualAssistantResult>(`${this._apiUrl}/users`, options);

由於棄用RequestOptions ,因此不支持在 DELETE 請求中將數據作為正文發送。

如果您查看DELETE的定義,它看起來像這樣:

    delete<T>(url: string, options?: {
      headers?: HttpHeaders | {
         [header: string]: string | string[];
        };
      observe?: 'body';
      params?: HttpParams | {
          [param: string]: string | string[];
         };
      reportProgress?: boolean;
      responseType?: 'json';
      withCredentials?: boolean;
     }): Observable<T>;

您可以將有效負載與 DELETE 請求一起作為選項對象中參數的一部分發送,如下所示:

this.http.delete('http://testAPI:3000/stuff', { params: {
    data: yourData
     }).subscribe((data)=>. 
        {console.log(data)});

但是,請注意 params 只接受字符串string[]形式的數據,因此除非將其字符串化,否則您將無法發送自己的接口數據。

@angular/http在 http.js 中的定義:

刪除(網址,選項)

該請求不接受正文,因此您唯一的選擇似乎是 URI 中的數據。

我發現了另一個主題,其中引用了對應的 RFC,其中包括: 如何在 ajax DELETE 請求中傳遞數據而不是標頭

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM