Struggling to retrieve the HTTP Response Code from an Angular Service

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'];
           }
        */            
      }
    );
  }
}

Answer №1

Ensure to specify the observe value:

When writing your service method:

getInfo(params){
  return this._httpConnection.fetch(_URL, {params: params, observe: 'response'});
}

And in your component code:

this._myService.getInfo(searchParam).subscribe(
  (res: HttpResponse<any>) => {
    console.log(res.status);   
  }
);

The response returned will be an HttpResponse instance. For further details, refer to the complete guide on reading the full response

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

The alignment of ngx-dropdown in the bottom sidebar element of Bootstrap 5 seems to be misaligned

Struggling with dropdown positioning? Check out the examples I created on stackblitz: As I was referring to examples from bootstrap-5, the issue I faced pertained to the user panel in the sidebar (both collapsed and expanded view): example 1 example 2 ...

ERROR: The use of @xenova/transformers for importing requires ESM

When working with my Node.js application, I usually start by importing the necessary modules like this: import { AutoModel, AutoTokenizer } from '@xenova/transformers'; Afterwards, I utilize them in my code as shown below: const tokenizer = awai ...

Undefined property encountered while trying to set a property during the invocation of a template

I am currently working on creating a dynamic popup using Bootstrap where I want to add a header, body, and footer dynamically to an HTML template for a modal. However, when I run the code, I encounter errors in the browser console because the values for th ...

Having trouble with Angular 2 Routing and loading components?

I am facing an issue with Angular 2 where it is searching for my component in app/app/aboutus.component, but I cannot pinpoint the source of the problem. Here is my app.component.ts code: import { Component } from '@angular/core'; import { ROUT ...

I have an Observable but I need to convert it into a String

Seeking assistance with Angular translation service and Kendo.UI components. In the Kendo.UI documentation, it mentions the use of MessageService for component translation implementation. To achieve this, an abstract class must be extended containing a m ...

Strategies for implementing searchbar filtering in Ionic3 and Angular5 data manipulation

I'm having trouble displaying product names on my search.html page based on the search bar input. I've tried using the Ionic searchbar component but it's not working. Can anyone help me with this issue? If there's an alternative solutio ...

Tips for ensuring radiobuttons are defaulted to unchecked within a shared form group in Angular 2 and beyond

The radio buttons are linked to data from the database (Web-API). Below are my complete code snippets: component.html <!-- list of Questions --> <div formArrayName="questions"> <!-- <div *ngFor="let que of Questions; let ...

What is the mechanism behind property binding in Angular 2? Can you explain what is happening in this specific scenario?

Being a novice in the realm of Angular 2, I find myself grappling with doubts related to property binding. While this particular example seems to work fine, I can't help but wonder about what exactly goes on behind the scenes. Within my component vi ...

The ng command seems to be malfunctioning when executed from a separate directory

After selecting a different folder for my new angular project, I encountered an error every time I tried to run an ng command: 'ng' is not recognized as an internal or external command, operable program or batch file. I attempted to resolve ...

Angular - Loading images on demand

I've recently started learning Angular and Typescript, and I've run into an issue that I could use some help with. I want to implement lazy loading for all the images in my application by adding the loading="lazy" attribute to each < ...

Upon upgrading @types/angular, I encountered error TS2694 stating that the namespace 'angular' does not have an exported member 'xxx'

Following the upgrade of angular and @types/angular to version 1.6.x, an array of TS2694 errors suddenly appeared: error TS2694: Namespace 'angular' does not include an exported member named 'material' error TS2694: Namespace 'ang ...

Organize the menu in Angular by sorting it alphabetically

I am currently exploring a way to organize the buttons inside the menu in alphabetical order using a function in the TypeScript file. Please see the code snippet below, which utilizes Angular Material. <mat-menu #menu3="matMenu" [overlapTrig ...

Angular 4 is displaying an error message indicating that the expression has been modified after being initially verified

I've been utilizing Angular Material within my Angular 4 application. There seems to be an issue when attempting to utilize the MatSnackBar in the ngAfterViewInit(). The error I encounter is as follows: ExpressionChangedAfterItHasBeenCheckedError: ...

Help needed: Encountered an error stating "Module not found: Error can't resolve 'child_process', any solutions to resolve this issue?

I'm currently in the process of developing a JupyterLab extension using TypeScript. After successfully incorporating the package "@types/node" to access functionalities like 'require('http')', I encountered an issue when attemptin ...

What is the best method for resetting the user state to null?

I'm currently utilizing VueX in Nuxt with Typescript. My goal is to set the initial state of my user to null. When I try setting state.authenticatedUser:null, everything works smoothly. However, when I attempt to assign an IAuthenticatedUser type to i ...

The authentication system in Django rest-auth functions smoothly with superusers, but encounters issues with non-superuser accounts, resulting in the error message "Unable to log in

Is there a reason why rest-auth is only working correctly with superusers? I'm encountering an error when trying to log in a user without staff or superuser permissions, as shown below. The user gets registered successfully though. { "non_field_e ...

Having trouble accessing the application on localhost

I'm diving into the world of Docker! I'm looking to build a personalized docker image for an Angular application using a Dockerfile. I've successfully created the image and got the container up and running, but unfortunately, I'm unable ...

Identifier for md-radio-group

In my Angular 4 Material application, I have a set of radio buttons grouped together: <md-radio-group fxLayout fxLayoutAlign="center center" fxLayoutGap="30px"> <md-radio-button value="1">Date</md-radio-button> <md-radio-butto ...

Angular 2 Application faces rejection by .NET API due to absence of "Access-Control-Allow-Origin"

How can I specify the content type as application/json format? I have a POST method that is used to add a customer's contact. I have created a WebAPI with the following code snippet... [Produces("application/json")] [Route("api/[controller]")] publi ...

What is the best way to compare two TypeScript object arrays for equality, especially when some objects may have multiple ways to be considered equivalent

Currently, I am in the process of developing a cost function for a game where players are given a set of resources in their hand. The resources can be categorized into different types such as Fire, Air, Water, Earth, Good, Evil, Law, Chaos, and Void. Thes ...