如何获取响应 POST 请求的状态码?我的服务方法返回:
return this.httpClient.post(url, body, {observe: 'response'})
.catch(HandleError.handleErrorClient);
在我的组件中,我调用此方法并订阅:
.subscribe(
res => {
console.log(res);
console.log(JSON.stringify(res));
this.responseStatus = res.status;
console.log(this.responseStatus);
},
err => {
this.responseStatus = err.status;
});
但是在浏览器控制台中什么都没有 - 但是当请求包含错误时,然后this.responseStatus = err.status
返回正确的状态代码,但res.status
或res
不包含状态代码,只有响应正文。
编辑:
零件:
responseStatus: number;
loginUser() {
this.loginData = this.loginForm.getRawValue();
this.userLoginService.loginUser(this.loginData)
.subscribe(
res => {
console.log('bla bla');
this.responseStatus = res.status;
},
err => {
console.log(err.status); //401
console.log(err.error.error); //undefined
console.log(JSON.parse(err.error).error); //unauthorized
this.responseStatus = err.status;
});
}
服务:
import {Http} from "@angular/http";
import {HttpClient} from '@angular/common/http';
...
constructor(private http: Http, private httpClient: HttpClient) {
}
loginUser(loginData: LoginForm) {
return this.httpClient.post(this.loginURL, loginData, {observe: 'response'})
.catch(HandleError.handleError);
}
处理错误.ts
export class HandleError {
static handleError(error: Response | any) {
let errMsg: string;
if (error instanceof Response) {
const body = error.json() || '';
const err = body.error || JSON.stringify(body);
errMsg = `${error.status} - ${error.statusText || ''} ${err}`;
} else {
errMsg = error.message ? error.message : error.toString();
}
console.error(errMsg);
return Observable.throw(error);
}
}
POST:/api/login
我登录正确,但仅此而已......我期望在浏览器控制台中:console.log('bla bla');
。Http
没有问题。