Http의 본문.Angular2에서 DELETE 요청
Angular 2 프론트엔드에서 다소 RESTful한 API와 대화하려고 합니다.
컬렉션에서 일부 항목을 제거하려면 removée 고유 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 에 수 .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 5 에서requestdelete시체를 보내려고요 에 대한 문서에 대한 .deleted이(가) .body되어 있습니다 즉, .
import { HttpClient, HttpHeaders } from '@angular/common/http';
this.http.request('DELETE', url, {
headers: new HttpHeaders({
'Content-Type': 'application/json',
}),
body: { foo: bar }
});
은 실제로 를 수 .Angular2 HTTP를 보내기 bodyDELETErequest방법. 다음 방법:
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)});
로 .RequestOptionsArgsn에는 .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);
}
각도 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);
}
Angular 13에서 이 내용은 제게 적합합니다.
const options = {
headers: this._headers,
body: JSON.stringify(user)
};
return this._http.delete<DeleteVirtualAssistantResult>(`${this._apiUrl}/users`, options);
REST는 DELETE 요청으로 본문 포함을 방지하지 않지만 가장 표준화된 쿼리 문자열을 사용하는 것이 좋습니다(데이터를 암호화할 필요가 없는 경우).
다음과 같이 함으로써 각도 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);
}
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)});
그러나 매개 변수는 데이터를 문자열 또는 문자열[]로만 허용하므로 문자열을 지정하지 않으면 자신의 인터페이스 데이터를 보낼 수 없습니다.
@angular/http에서 http.js로 정의:
삭제(url, 옵션)
요청이 본체를 수락하지 않으므로 URI에 있는 데이터만 수락하는 것이 유일한 방법인 것 같습니다.
RFC와 관련된 다른 주제를 찾았는데, 그 중에서도 다음과 같은 것이 있습니다.ax DELETE 요청에서 헤더 이외의 데이터를 전달하는 방법
언급URL : https://stackoverflow.com/questions/38819336/body-of-http-delete-request-in-angular2
'programing' 카테고리의 다른 글
| 아이폰용 자동 테스트 (0) | 2023.09.26 |
|---|---|
| Spring Security()의 역할이 작동하지 않습니다. (0) | 2023.09.21 |
| PowerShell의 Format-List에서 출력을 문자열로 가져오려면 어떻게 해야 합니까? (0) | 2023.09.21 |
| 게시물의 최상위 카테고리를 얻기 위한 워드프레스 기능? (0) | 2023.09.21 |
| cst디오 스트림 vs ios 스트림 스트림 스트림? (0) | 2023.09.21 |