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

Can a ng-repeat value be assigned to a text input field?

<tr ng-repeat="person in users" ng-class="{'chosen': person.AdmissionID == currentSelection}" ng-click="selectRow(person.AdmissionID)"> <td>{{person.AdmissionID}}</td> <td>{{person.AdmissionNumber}}</td> ...

What is the best way to continuously loop an image from left to right and right to left indefinitely using JavaScript?

As part of the challenge, I am tasked with creating a Pacman game using HTML, CSS, and JavaScript. One key aspect is to control the movement of the ghosts throughout the game. However, I am facing an issue with the current function that controls the ghost& ...

The functionality of the Bootstrap collapse menu is not compatible with Angular

I'm experiencing difficulties with implementing the "collapse" effect in the menu using bootstrap and angular. I have set up the layout separately and everything seems to be functioning correctly, but as soon as I integrate angular, the menu stops wor ...

Having difficulties with the edit function in JavaScript To Do Application

After creating an edit button to modify a task, it functions properly for the initial task I create. However, when attempting to edit subsequent tasks, the edit function defaults back to modifying the input of the first task instead. With each new ta ...

An array of objects in JavaScript is populated with identical data as the original array

I am attempting to gather all similar data values into an array of objects. Here is my initial input: var a = [{ name: "Foo", id: "123", data: ["65d4ze", "65h8914d"] }, { name: "Bar", id: "321", data: ["65d4ze", "894ver81"] } ...

Finding the most suitable location for storing interfaces and type aliases

In my angular2 project, I employ custom interfaces and type aliases. For instance, as part of a component to display a list of products, I define the Product interface: export interface Product { id: number; name: string; price: number; } Dec ...

Retrieve the id of an element from a JSON object

Dealing with quotes, single or double, can sometimes pose a challenge. I am working on a JavaScript function that sends data to a PHP file and receives a JSON response. Everything seems to be functioning correctly, except for the part where I need to out ...

Troubleshooting problems with dates in jQuery AJAX

Hey, I recently worked on formatting dates in jQuery Ajax. After fetching a date value from the database, I converted it to the format dd-MM-YYYY. However, there seems to be an issue where I'm receiving the previous month. For example, if the database ...

React Hooks findByID method is throwing an error stating that it cannot read the property 'params' because it is undefined

As I dive into learning React hooks, I'm realizing that it's crucial to stay up-to-date with the latest trends in web development. Despite hours of research and tinkering around, I can't seem to wrap my head around some key concepts. The fac ...

Vue.js component function "not instantiated within the object"

I recently started learning vue.js and decided to use vue-cli to set up a new project. As I was working on adding a method to a component, I encountered some issues: <template> <div> <div v-for="task in $state.settings.subtasks& ...

AngularJS grid designed to emulate the functionalities of a spreadsheet

I have been facing challenges with Angular while attempting to recreate a spreadsheet layout in HTML using ng-repeat. Despite extensive research, I have not found a solution. My goal is to display data in a table format as shown below: <table> & ...

Angular is throwing an error because it cannot find the definition for

Embarking on a tutorial journey to dive into Angular setup. Facing a persistent error in my code... Error: [$injector:undef] http://errors.angularjs.org/1.6.0/$injector/undef?p0=Bear Listing the order of files within the <head> tag in the html ...

Chrome successfully handles cross-domain AJAX calls with Windows authentication, whereas Firefox encounters issues with the same functionality

I am facing an issue with my WCF service that uses windows authentication. When I call this service using ajax in Google Chrome, everything works perfectly as the credentials are cached. However, in Firefox, I am receiving a 401 unauthorized error. I would ...

Maintain the URL state while logging in using angular-oauth2-oidc

In our Angular application, we utilize angular-oauth2-oidc for authentication management with the Code Flow and PKCE. To enable automatic login for users upon app visit, we initialize our app as follows: this.oauthService.configure(authModuleObject); this. ...

Steps for eliminating QRcode warning in npmjs package

Issue: Warning Message (node:24688) ExperimentalWarning: buffer.Blob is an experimental feature. This feature could change at any time (Use `node --trace-warnings ...` to show where the warning was created) Seeking Solution: How can I prevent this warning ...

Extracting Node.js data within a Node.js script

Can a node.js file be parsed to execute part of the code within another node.js file? I am attempting to parse a node.js file from within a different script. I do not have control over the contents of the file, but it always contains a function called get ...

A programming element that is capable of accessing a data member, but mandates the use of a setter method for modifications

I am unsure whether I need a class or an interface, but my goal is to create an object with a member variable that can be easily accessed like a regular variable. For example: interface LineRange { begin: number; end: number; } However, I want th ...

The nightwatch.js script is halting operations once the test suite has been completed

Recently, I've implemented functional test automation using nightwatch.js. However, I encountered an issue where the test pauses after the test suite is completed, failing to end the process. Below is a snippet of the code: var afterSuite = function( ...

What are the steps to resolve the issue of "npm ERR! EEXIST: file already exists, rename" occurring with non-existent files?

Welcome to my first question post. (Please be kind if I make mistakes.) I am using node version 5.6.0. For an assignment, I downloaded a JS web app but am encountering an error that is preventing me from working on it: S:\PersonalCloud\jennyly ...

Encountering a hiccup while attempting to implement ngx-translate in an Angular library

I'm in the process of developing an Angular library, and I need to incorporate ngx-translate. In my other applications, I typically add TranslateModule.forRoot in the app.module file. import .... // AoT requires an exported function for factories exp ...