In my current project, I am utilizing Angular 4 for frontend development and Django REST Framework (DRF) as the backend. The issue I am facing is with extracting the Response JSON and HTTP Response Code separately from the DRF end in the form of a response tuple
Response(data=vJSON, status=vStatus)
, which is returned by view functions like GET
, PUT
, POST
, etc.
The challenge lies in not being able to retrieve the HTTP Response Code and Response JSON individually from the Angular side. Separating these two components is crucial for displaying error messages on the UI when the HTTP Code is either 200 or 201, a task that currently eludes me.
My current setup only allows me to access the JSON part of the response received from the service function in the component function. How can I extract the HTTP Code along with the Response JSON independently?
Below are snippets of the code involved:-
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 [ In comment section below inside the code I have mentioned my requirement ]
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'];
}
*/
}
);
}
}