我需要向API发送POST请求,如果响应代码== 400,则从响应中获取信息。 http://joxi.ru/l2ZM0KES0M8ZmJ
public contactUsSendPost(params): Observable<{}> {
return this.contactUsSendPostWithHttpInfo(params)
.map((response: Response) => response.json());
}
public contactUsSendPostWithHttpInfo(params): Observable<Response> {
const path = this.basePath + `/contact-us/send`;
let queryParameters = new URLSearchParams();
let headers = new Headers(this.defaultHeaders.toJSON());
let formParams = new URLSearchParams();
headers.set('Content-Type', 'application/x-www-form-urlencoded');
headers.set('Accept', 'application/json');
if (params.email !== undefined) {
formParams.set('email', <any>params.email);
}
if (params.fullName !== undefined) {
formParams.set('fullName', <any>params.fullName);
}
if (params.question !== undefined) {
formParams.set('question', <any>params.question);
}
let requestOptions: RequestOptionsArgs = new RequestOptions({
method: RequestMethod.Post,
headers: headers,
body: formParams.toString(),
search: queryParameters
});
return this.http.request(path, requestOptions);
}
然后我试图从服务中获得响应,但无法获得响应体。
this.fqService.contactUsSendPost(formValues).subscribe(
data => console.log(data ),
err => console.log(err) <------
);
那么,如何从具有400状态代码的http响应获得角度为2的响应体?
答案 0 :(得分:0)
您只需要捕获observable上的错误,请参阅下面的修改代码。
public contactUsSendPost(params): Observable<{}> {
return this.contactUsSendPostWithHttpInfo(params)
.map((response: Response) => response.json())
.catch(this.handleError);
}
public contactUsSendPostWithHttpInfo(params): Observable<Response> {
const path = this.basePath + `/contact-us/send`;
let queryParameters = new URLSearchParams();
let headers = new Headers(this.defaultHeaders.toJSON());
let formParams = new URLSearchParams();
headers.set('Content-Type', 'application/x-www-form-urlencoded');
headers.set('Accept', 'application/json');
if (params.email !== undefined) {
formParams.set('email', <any>params.email);
}
if (params.fullName !== undefined) {
formParams.set('fullName', <any>params.fullName);
}
if (params.question !== undefined) {
formParams.set('question', <any>params.question);
}
let requestOptions: RequestOptionsArgs = new RequestOptions({
method: RequestMethod.Post,
headers: headers,
body: formParams.toString(),
search: queryParameters
});
return this.http.request(path, requestOptions);
}
private handleError (error: Response | any) {
return Observable.throw(error.code);
}
答案 1 :(得分:0)
您可以升级到角度为4.3及以上的HttpClient模块,
如果您将整个请求对象作为输入传递给http.request方法,您将获得一个完整的响应对象。