我使用Angular 4作为前端& Django REST Framework(DRF)作为我项目的后端。从DRF结束,我将返回 Response JSON &来自Response(data=vJSON, status=vStatus)
/ GET
/ PUT
等视图函数的响应元组POST
形式的 HTTP响应代码
问题是,从Angular结束我无法提取HTTP响应代码&响应JSON 单独。这是我需要的,因为HTTP响应代码可以帮助我在UI端显示错误消息,如果HTTP代码不是200或201,我无法做到。
我只从服务函数返回到组件函数的响应中获取JSON部分。那么如何单独获取HTTP代码和响应JSON呢?
以下是代码: -
views.py
from rest_framework.response import Response
from rest_framework import status
..
..
def get(self, request, format = None):
vJSON = {}
try:
vHTTPStatus = status.HTTP_200_OK
# All logics are here
..
..
except Exception as e:
vHTTPStatus = status.HTTP_400_BAD_REQUEST
finally:
return Response(data=vJSON, status=vHTTPStatus)
app.service.ts
import {Observables} from 'rzjs/Observable';
import {HttpClient, HttpParams} from '@angular/common/http';
export class AppService{
private _URL: string;
constructor(private _httpConn: HttpClient){
this._URL = 'http://xx.xx.xx.xxx/8000/myapi/';
}
getResponse(pParams){
return this._httpConn.get(_URL, {params: pParams});
}
}
app.component.ts [在我已提及要求的代码内的评论部分]
import {AppService} from ./app.service;
import {HttpParams} from '@angular/common/http';
export class AppComponent {
textAreaValue: string;
constructor(private _myService: AppService){
this.textAreaValue = "";
}
fetchData(): void{
let vSearchParam = new HttpParams();
vSearchParam = vSearchParam.append('id', '1000001');
this._myService.getResponse(vSearchParam).subscribe(
response => {
..
/* Here are the logics how to use the response JSON */
console.log(response);
..
..
/* This is what I want
if (response.status != 200) {
this.displayError("There is a connection issue!");
this.textAreaValue = "Unable to show records!";
}
else{
this.textAreaValue = response.data['value'];
}
*/
}
);
}
}
答案 0 :(得分:2)
您应该设置观察值:
所以在你的服务方法中:
getResponse(pParams){
return this._httpConn.get(_URL, {params: pParams, observe: 'response'});
}
在你的组件中:
this._myService.getResponse(vSearchParam).subscribe(
(response: HttpResponse<any>) => {
console.log(response.status);
}
);
响应将是HttpResponse对象。 您可以找到完整的指南reading-the-full-response