Angular 8 Issue: Absence of _body and Headers in Response

Our back-end code is written in C# within the .NET environment, targeting the 4.6.1 framework. Recently, our front-end was upgraded from Angular 4 to Angular 8. During this upgrade, webpack transitioned from version 2.3 to version 4.41 and typescript from version 2.2 to 3.2.4.

Despite these changes, the core code itself has remained unchanged.

C#:

public override Task OnAuthorizationAsync(HttpActionContext actionContext, CancellationToken cancellationToken)
{
    var reject = false;
    var principal = actionContext.RequestContext.Principal as ClaimsPrincipal;

    if (principal == null || !principal.Identity.IsAuthenticated || reject) {
        actionContext.Response = actionContext.Request.CreateResponse(HttpStatusCode.Unauthorized,
            new { error = "Unauthorized request for Impersonate Mode" },
            actionContext.ControllerContext.Configuration.Formatters.JsonFormatter);
        return Task.FromResult<object>(null);
    }

    return Task.FromResult<object>(null);
}

Typescript:

actionErrorResponseHandler(response: Response) {
    if(response.status === 401){
        if(response.text().includes("Impersonate")){
            this.displayText = ImpersonateRejectText;
        }
        this.show();
    }
}

(EDIT) Usage example:

setupPopUpModal(modalHeader: string, displayText: string){
    this.accountService.accountShowPopUpModal()
    .pipe(catchError((response: Response) => this.rejectModal.actionErrorResponseHandler(response)))
    .subscribe((result: string) => {
        if(result == "Done"){
            this.modalHeader = modalHeader;
            this.displayText = displayText;
            this.messageBoxModal.show();
        }            
    })
}

Previously, everything was functioning correctly. However, after the upgrade, an error message stating "e.text is not a function" started appearing.

Upon inspecting Chrome's developer tools, the response prior to the upgrade looked like this:

https://i.sstatic.net/Cu3Ve.png

And post-upgrade, it looked like this:

https://i.sstatic.net/SIbKH.png

The issue stems from the reference to the .text() function attempting to retrieve the body as a string, which no longer exists. The desired message can now be found in e.error instead of response.error, with Angular/Typescript syntax differing on how to access it.

I suspect that I need to approach building and parsing the response differently, but I have been unable to locate relevant documentation on this topic. Any assistance would be greatly appreciated.

Answer №1

Could the previous version of Angular have been before 4.3?

In Angular 4.3, there was a change in the way regular HTTP requests are made from "Http" to "HttpClient". The main difference is that you only receive the (json) response body as a result, rather than the entire response object. If the request is unsuccessful (except for a 401 error), it will throw an error.

To handle this error, you need to catch it and manage it appropriately. One common approach is using RxJs to handle the response, which would transform your code like this:

let response: SomeTyp;
this.httpClient.get<SomeTyp>('myBackendUrl').subscribe( (result) => response = result);

If a 400 error occurs in the backend call, the regular subscription won't run, leaving response empty. One solution is to manage the error within the subscribe function:

let response: SomeTyp;
this.httpClient.get<SomeTyp>('myBackendUrl').subscribe( 
  (result) => response = result,
  (errorCase) => this.handleTheError(errorCase)
);

private handleTheError(errorCase:ttpErrorResponse):void {
  if(response.status === 401){
    if(response.text().includes("Impersonate")){
      this.displayText = ImpersonateRejectText;
      return
    }
  }
  throw Error('Unexpected Backend Response');
}

Alternatively, you can handle errors within the stream using catchError:

let response: SomeTyp;
this.httpClient.get<SomeTyp>('myBackendUrl').pipe(
  catchError( (errorCase:ttpErrorResponse) => // Handle the error )
).subscribe( 
  (result) => response = result
);

The advantage of using "catchError" is that you can gracefully handle expected errors by returning a valid value, which will be processed by the subscribe function as if it were a successful response. If the error cannot be managed gracefully, you can still throw it:

return throwError(errorCase);

Subsequently, you can handle the error in the subscribe function.

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

Contrasting between betting text and console error logging in Angular

Currently working on an Angular application and exploring the best practices for error logging. I'm pondering whether to opt for console logging or text-based logging. Text-based logging seems beneficial as it stores historical error data on the serv ...

Encountering an error with loading in Angular may require a suitable loader

I am currently working on integrating an AWS QuickSight dashboard into an Angular application. For implementation in Angular, I am referring to the following URL: https://github.com/awslabs/amazon-quicksight-embedding-sdk Could someone provide me with sa ...

"Error: The React TypeScript variable has been declared but remains

Seeking guidance on ReactTS. I'm puzzled by the undefined value of the variable content. Could someone shed light on why this is happening and how to assign a value to it for passing to <App />? The issue persists in both the index.tsx file and ...

Error encountered when attempting to insert data into a PostgreSQL database using Node.js and Sequelize

I'm currently using the node sequelize library to handle data insertion in a postgress database. Below is the user model defined in the Users.ts file: export class User extends Sequelize.Model { public id!: number; public name: string; public ...

Creating an interface that features a function capable of accepting its own type and interacting with other interface implementations

interface I { test: (a: I) => boolean; } class Test implements I { //constructor (public additional: number) {} test (a: Test) { return false; } } The code is functioning, however, when we remove the comment from the constructor line, it stops ...

Learn the process of invoking Firebase Functions through AngularFire

My project involves creating a Firebase Cloud function using functions.https.onRequest to act as an API that returns JSON data from the Firebase Realtime database. After some research, I discovered functions.https.onCall, which provides authentication fun ...

Issue: The code is throwing an error "TypeError: Cannot read property 'push' of undefined" in the JavaScript engine "Hermes

Can anyone assist me with filtering an array of objects in a TypeScript React Native project using state to store array values and filter objects in the array? Having trouble with the following error in the mentioned method: LOG after item LOG inside ...

What is the best way to retrieve a property with a period in the method name in JavaScript?

One dilemma I'm facing is trying to access the tree.removenode method through chartContext in Angular. It's been a challenge for me to understand how to achieve this. https://i.stack.imgur.com/yG7uB.png ...

What is the reason for my Firestore listener consistently retrieving data from the server despite having offline persistence enabled?

Incorporating Firebase JavaScript Modular Web Version 9 SDK into my Vue 3 / TypeScript application. My understanding is that when utilizing real-time listeners with offline persistence in Firestore, the process should proceed as follows: Upon initializat ...

Utilizing Angular to Handle Undefined Variables in String Interpolation

Seeking a way to showcase data obtained from an external API on a webpage using Angular's string interpolation. If no data is retrieved or is still pending, the aim is to display 'N/A'. An attempt was made following this method, but encoun ...

Tips for showing nested array values in Angular 8

I'm new to using angular and I'm attempting to display values from an array within another array in a table format. Here is my JSON array that I'd like to display in rows: { "data": { "Influencer": [ { ...

What is the necessity of Angular reflect polyfill for JIT mode?

I recently came across information on the Angular browser support page discussing the JIT compilation and the ES7/reflect polyfill, stating: It is possible to remove if you always utilize AOT and solely rely on Angular decorators. However, a couple of ...

Issue: Unrecognized element type in next.js while starting development server

Every time I run npm run dev, I encounter the following error: Error: Element type is invalid: expected a string (for built-in components) or a class/function (for composite components) but got: undefined. You likely forgot to export your component from th ...

Definition for intersecting types

I am trying to define a function that can take two objects of different types but with the same keys: function myFunc(left, right, keys) { // simplified: for (const key of keys) { console.log(key, left[key] === right[key]) } return { left, rig ...

transformed an Angular 2 web application into a sleek and functional mobile application

I am looking to convert my basic angular2 web application into a mobile app using cordova. Is there a way to achieve this without relying on Ionic or nativeScript? ...

What is the best way to update my list after deleting an item using promises?

I am facing an issue in my Angular application where I need to update a list after deleting an item, but I am unsure about how to achieve this using promises. delete(id: any) { this.missionService.deleteMission(id); // .then((res) => { // ...

Encountering the issue of receiving "undefined" in node.js after submitting data from an Angular form

I am facing an issue where I am getting 'undefined' in the backend (node.js) when I submit data from angular forms, even though I have used body-parser to parse the incoming data. server.js const express= require("express"); const app= ...

Tips for accessing and modifying local files in Angular 2

Is there a method in Angular 2 to access files from an absolute path? I have utilized the 'filesaver' library for file saving, storing the files locally in txt/json formats. For instance: let blob = new Blob([document.getElementById(&apos ...

Exploring the Functionality of HTML Anchor Link Fragment within Angular 6

I've been working on an Angular 6 project where I've disabled the hash-location-strategy, removing # from the URL. As a result of this change, a link like: <li routerLinkActive="active"> <a [routerLink]="['/settin ...

Getting started with html2canvas: A beginner's guide

So here's a seemingly simple question... I'm diving into new territory and stumbled upon http://html2canvas.hertzen.com with a straightforward tutorial. After successfully running the command npm install -g html2canvas, I hit a roadblock. Where e ...