Angular2 中 Http.DELETE 个请求的 Body
Body of Http.DELETE request in Angular2
我正在尝试与来自 Angular 2 前端的 RESTful API 交谈。
要从 collection 中删除某些项目,除了要删除的唯一 ID(可以附加到 url)之外,我还需要发送一些其他数据,即身份验证令牌,一些 collection 信息和一些辅助数据。
我发现最直接的方法是将身份验证令牌放入请求 Headers,并将其他数据放入 body.
但是,Angular 2 的 Http 模块不太同意带有 body 的 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.
现在,我是不是做错了什么syntax-wise?我很确定每个 RFC
都支持 DELETE body
是否有更好的方式发送该数据?
或者我应该将它转储到 headers 中并结束它?
任何对此难题的见解都将不胜感激
http.js 中的定义来自 @angular/http:
delete(url, options)
该请求不接受正文,因此您唯一的选择似乎是接受 URI 中的数据。
我找到了另一个主题,其中引用了相应的 RFC,其中包括:
How to pass data in the ajax DELETE request other than headers
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);
});
您实际上可以使用 request
方法欺骗 Angular2 HTTP
发送带有 DELETE
的 body
。是这样的:
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
相同的结果
我希望这对您有所帮助并且我不会迟到。我认为 angular 的人在这里不允许通过 delete 传递正文是错误的,尽管不鼓励这样做。
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;
});
Notice that body
is passed through RequestOptions
下面是 Angular 4/5 与新 HttpClient 的相关代码示例。
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 5 中,我必须使用 request
方法而不是 delete
来发送正文。 delete
方法的文档不包含 body
,但包含在请求方法中。
import { HttpClient, HttpHeaders } from '@angular/common/http';
this.http.request('DELETE', url, {
headers: new HttpHeaders({
'Content-Type': 'application/json',
}),
body: { foo: bar }
});
下面是 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);
}
如果你使用 Angular 6,我们可以将主体放在 http.request
方法中。
你可以试试这个,对我来说很管用。
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 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);
}
自从 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>;
您可以在 options 对象中作为 params 的一部分将负载与 DELETE 请求一起发送,如下所示:
this.http.delete('http://testAPI:3000/stuff', { params: {
data: yourData
}).subscribe((data)=>.
{console.log(data)});
但是注意params只接受数据为string或string[]所以你将无法发送自己的接口数据,除非您将其字符串化。
对于 angular 10,您还可以使用通用请求格式和 DELETE 方法:
http.request('DELETE', path, {
body:body,
headers: httpHeaders,
params: ((params != null) ? params : new HttpParams())
})
我正在尝试与来自 Angular 2 前端的 RESTful API 交谈。
要从 collection 中删除某些项目,除了要删除的唯一 ID(可以附加到 url)之外,我还需要发送一些其他数据,即身份验证令牌,一些 collection 信息和一些辅助数据。
我发现最直接的方法是将身份验证令牌放入请求 Headers,并将其他数据放入 body.
但是,Angular 2 的 Http 模块不太同意带有 body 的 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.
现在,我是不是做错了什么syntax-wise?我很确定每个 RFC
都支持 DELETE body是否有更好的方式发送该数据?
或者我应该将它转储到 headers 中并结束它?
任何对此难题的见解都将不胜感激
http.js 中的定义来自 @angular/http:
delete(url, options)
该请求不接受正文,因此您唯一的选择似乎是接受 URI 中的数据。
我找到了另一个主题,其中引用了相应的 RFC,其中包括: How to pass data in the ajax DELETE request other than headers
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);
});
您实际上可以使用 request
方法欺骗 Angular2 HTTP
发送带有 DELETE
的 body
。是这样的:
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
我希望这对您有所帮助并且我不会迟到。我认为 angular 的人在这里不允许通过 delete 传递正文是错误的,尽管不鼓励这样做。
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;
});
Notice that
body
is passed throughRequestOptions
下面是 Angular 4/5 与新 HttpClient 的相关代码示例。
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 5 中,我必须使用 request
方法而不是 delete
来发送正文。 delete
方法的文档不包含 body
,但包含在请求方法中。
import { HttpClient, HttpHeaders } from '@angular/common/http';
this.http.request('DELETE', url, {
headers: new HttpHeaders({
'Content-Type': 'application/json',
}),
body: { foo: bar }
});
下面是 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);
}
如果你使用 Angular 6,我们可以将主体放在 http.request
方法中。
你可以试试这个,对我来说很管用。
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 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);
}
自从 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>;
您可以在 options 对象中作为 params 的一部分将负载与 DELETE 请求一起发送,如下所示:
this.http.delete('http://testAPI:3000/stuff', { params: {
data: yourData
}).subscribe((data)=>.
{console.log(data)});
但是注意params只接受数据为string或string[]所以你将无法发送自己的接口数据,除非您将其字符串化。
对于 angular 10,您还可以使用通用请求格式和 DELETE 方法:
http.request('DELETE', path, {
body:body,
headers: httpHeaders,
params: ((params != null) ? params : new HttpParams())
})