I am using Angular 4 as frontend & Django REST Framework (DRF) as backend in my project. From the DRF end I am returning both the Response JSON & HTTP Response Code in form of a response tuple Response(data=vJSON, status=vStatus)
, from the view functions such as GET
/PUT
/POST
etc.
The problem is, from Angular end I am unable to extract the HTTP Response Code & the Response JSON separately. This I need because the HTTP Response Code can help me to display error messages in UI end if the HTTP Code is not 200 or 201, that I am unable to do.
I am getting only the JSON part from the response returned by the service function to the component function. So how to get the HTTP Code along with the Response JSON separately?
Below are the codes:-
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'];
}
*/
}
);
}
}
You should set the observe value:
So in your service method:
getResponse(pParams){
return this._httpConn.get(_URL, {params: pParams, observe: 'response'});
}
And in your component:
this._myService.getResponse(vSearchParam).subscribe(
(response: HttpResponse<any>) => {
console.log(response.status);
}
);
The response will be an HttpResponse object. You can find a complete guide reading-the-full-response