ERROR UnhandledTypeError: Unable to access attributes of null (attempting to retrieve 'pipe')

When I include "{ observe: 'response' }" in my request, why do I encounter an error (ERROR TypeError: Cannot read properties of undefined (reading 'pipe'))? This is to retrieve all headers.

    let answer = this.http.post<ResponseLoginHttp>(AUTH_API + "login", json_data, { observe: 'response' });
let answer2
answer.subscribe(value => {
  this.dataService.setResponceLoginHttp(value.body);
  answer2 = value.body
})
return answer2.pipe(
  map((data) => {
    return data;

  }),
  catchError((error) => {
    console.log("Error - ", error);
    throw new Error(error.message);
  })
);}

However, when I remove "{ observe: 'response' }", everything works as expected:

    let answer = this.http.post<ResponseLoginHttp>(AUTH_API + "login", json_data );
answer.subscribe(value => {
  this.dataService.setResponceLoginHttp(value);
})
return answer.pipe(
  map((data) => {
    return data;

  }),
  catchError((error) => {
    console.log("Error - ", error);
    throw new Error(error.message);
  })
);}

Is there a way to retrieve all the headers from the response without triggering the "ERROR TypeError: Cannot read properties of undefined (reading 'pipe')" error?

Answer №1

this is unrelated to your {observe: 'response'}

When you perform the following :

let answer = this.http.post<ResponseLoginHttp>(AUTH_API + "login", json_data, { observe: 'response' });
let answer2
answer.subscribe(value => {
  this.dataService.setResponceLoginHttp(value.body);
  answer2 = value.body
})
return answer2.pipe(

You are calling answer2 outside the subscribe and it is not yet defined. The subscribe function is asynchronous, meaning JavaScript will not wait for a response before executing the next line of code. Additionally, your answer2 variable will never be an Observable.

You should do something like this:

this.http.post<ResponseLoginHttp>(AUTH_API + "login", json_data, { observe: 'response' })
    .pipe(
        map((response: HttpResponse<ResponseLoginHttp>) => {
            // You can manipulate response.headers here
            return response.body;
        })      
     )
    .subscribe(
        value => this.dataService.setResponceLoginHttp(value),
        error => {
            console.log("Error - ", error);
            throw new Error(error.message);
        });

Or in a simpler way:

this.http.post<ResponseLoginHttp>(AUTH_API + "login", json_data, { observe: 'response' })
    .subscribe(
        response => {
            // You can work with response.headers here
            this.dataService.setResponceLoginHttp(response.body);
        }),
        error => {
            console.log("Error - ", error);
            throw new Error(error.message);
        });

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

Bovine without Redis to oversee queue operations

Can Bull (used for job management) be implemented without utilizing Redis? Here is a segment of my code: @Injectable() export class MailService { private queue: Bull.Queue; private readonly queueName = 'mail'; constructor() { ...

Creating a Route in Angular 2 for a Component other than the one initialized with the bootstrap function

I am currently in the process of working on a project involving Angular2. If you are interested in understanding why I need to do what I am about to explain, please take a look at this issue. The main component in my project is called AppComponent and it ...

Lost in a strange predicament

As I try to send props from my parent component to the child component, I am facing an issue where one of the children within the coin prop seems to be lost when I receive the props in componentWillReceiveProps(). This discrepancy becomes evident through t ...

Is it possible to incorporate conditionals within a jade template using JavaScript?

I've been working on a Jade template that includes some logic, but I seem to be encountering an issue. Here's the code snippet: #container -for(var col=0; col < 2 ;col++){ - if(col % 4 == 0){ .movie_row - } ...

A method for assigning a single event listener to multiple events in a React component

I find myself in a situation where I have two events, onClick and onSelect, both of which share the same event handler. I am wondering what the most efficient way to handle this scenario would be - should I create a common method and then call the event ...

Guide on verifying the presence of an alert with nodejs webdriver (wd)

I am currently facing a challenge when writing a test where I need to verify the existence of an alert, check its text if it is present, and then accept it. Although I have researched on platforms like Stack Overflow for solutions such as checking for ale ...

The div that scrolls gracefully within its boundaries

Currently, I am working on a task that involves a div containing images that need to be scrolled left and right. I have successfully implemented the scrolling functionality using jQuery. However, I now face the challenge of ensuring that the content stays ...

Tips for keeping your Angular CDK up to date and improving its performance

Having just started with Angular, I'm stuck trying to figure out why the update is throwing errors. Purpose: Update the cdk and material versions, then install file-saver. Command: npm update @angular/cdk How can I update my angular cdk? Here&apos ...

AngularJS allows for dynamic routing within applications

I'm a beginner with AngularJs and I've run into an issue where the URL changes but the page remains the same. Any help would be greatly appreciated. Here is my configuration: var app = angular.module('MyApp', ['ngResource',& ...

How can you prevent videos from constantly reloading when the same source is used in multiple components or pages?

How can we enhance loading performance in Javascript, React, or Next JS when utilizing the same video resource across various components on different pages of the website to prevent unnecessary reloading? Is there a method to store loaded videos in memor ...

`How can I effectively test a React.js page utilizing both Context and useEffect?`

I'm struggling with testing a page that uses Context and useEffect with Jest and Testing-library, can you offer any assistance? REPOSITORY: https://github.com/jefferson1104/padawan Context File: src/context/personContext.tsx import { createContext, ...

Animating a div using a changing scope variable in AngularJS

As a newcomer to Angular, I am looking to add animation to a div element using ng-click within an ng-repeat loop. Here is what I have attempted: app.js var app = angular.module( 'app', [] ); app.controller('appController', function($ ...

Output the name of the file while executing the ant process

Currently, I am utilizing YUI compressor within an ant build process to compress CSS and JavaScript files. I would like the compressor to display the name of each file it is processing as it goes along, so that in case of an error, I can easily pinpoint wh ...

Analyzing JSON information using an AJAX request from a local file

I have a PHP file on a web server that is executing queries to a MySQL database. Currently, I am testing a site on my local PC which utilizes a JS file with AJAX requests to retrieve JSON data from the mentioned PHP file. My question is whether it is fea ...

Implementing HTML page authentication with Identity ADFS URL through JavaScript

I have a basic HTML page that displays customer reports using a JavaScript function. The JavaScript makes an ajax call to retrieve the reports from a backend Spring REST API. In the Spring REST API, I have set up an endpoint "/api/saml" for authentication ...

Could you walk me through the details of this React function?

Currently, I have a function in place that retrieves products from the database to display on the eCommerce website's product page. Now, I am working on creating a similar function for user sign-in. Could you lend me a hand with this? I'm still ...

Differences Between Angular Event Emitter and Click Listener

I've been delving into Angular by exploring the "Your First App" section on their official website. One aspect that has caught my attention is the event emitter functionality. In the Parent Component (product-list): <app-product-alerts [produc ...

Experimenting with Angular component that dynamically updates based on observable service

For my Angular 4 project, I am currently testing the login() method within a component. This method relies on an Observable called authService, which can return either a success or an error: Here is the code that needs to be tested: login() { this.lo ...

Nest is unable to resolve the dependencies of the ItemsService. Ensure that the required argument at index [0] is present within the AppModule context

After following the Nest JS Crash tutorial from a Youtube Link, I encountered an error when importing an interface in the service. Nest seems unable to resolve dependencies of the ItemsService. It's important to ensure that the argument at index [0 ...

Guide on how to transmit an error message from PHP when handling a jQuery Ajax post request

Greetings! This is my inaugural inquiry, so please understand if I am a bit apprehensive. I am facing an issue in the following scenario... I have an Ajax request structured like this: $.ajax({ url: "test.php", method: "POST", data: { ...