When utilizing the catch function callback in Angular 2 with RxJs, the binding to 'this' can trigger the HTTP request to loop repeatedly

I have developed a method to handle errors resulting from http requests. Here is an example of how it functions:

public handleError(err: any, caught: Observable<any>): Observable<any> {

  //irrelevant code omitted
  this.logger.debug(err);//example of problem 
  return caught;
}

This method is called in the following manner (a sample method illustrating the error):

public makeHttpCall() {
    this.http.get("http://api.exmaple.com/getsomedata")
      .map(r=> r.json())
      .catch(this.handleError);
  }

The issue with the above code arises when this.logger.debug(err) is executed within the handleError method. At this point, instead of referring to the class where the http call originated from, this now refers to the CatchSubscriber.

View the reference change: https://i.stack.imgur.com/9yCzI.png

To resolve this, I modified .catch(this.handleError); to

.catch(this.handlError.bind(this))
;

After making this adjustment, this.logger.debug properly references the correct object. However, there is a new issue - the http request is being repeatedly triggered, as shown here:

https://i.stack.imgur.com/3pxPj.png

This repetitive calling only occurs after using .bind(this)

I am struggling to understand why this behavior is occurring

*********EDIT*********

Switching from .catch(handleError) to

.catch((a,b)=>handleError(a,b))
resolves the this reference problem but results in continuous spamming of the http request whenever it fails. If the request succeeds, it only triggers once.

Answer №1

Whenever a function is passed with .catch(this.handleError);, it loses its original context of this. To understand more about this issue, visit Why do I lose the context of this in Javascript?

A simple solution to this problem is to enclose the function call within a closure.

.catch((err, caught) => this.handleError(err, caught));

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

Have you encountered the error message "Error: Unexpected value 'DataTableModule' imported by the module 'DashboardModule'. Please remember to include a @NgModule annotation" while working on your project? Let's

Recently, I upgraded my Angular 4 project to Angular 7. The 'ng serve' command seems to work fine, but after logging into the application, I encountered an error in the console stating "Unexpected value 'DataTableModule' imported by the ...

How can I remove the currently clicked div element in HTML using Angular 4?

Here is the content of my div tag deleteObject(event) { console.log(event); console.log(event.target); event.target.hidden = true; //event.target.classList.add('class3'); } <div class="col" (click)="deleteObject($event)"&g ...

What is the procedure for obtaining FlowNode in the typescript ast api?

Trying to access and resolve foo and bar from the nodes variable. Upon examination in ts-ast-viewer, it is evident that TypeScript recognizes foo and bar within the nodes node under the FlowNode section (node -> initializer -> elements -> escaped ...

Can anyone help me with coloring Devanagiri diacritics in ReactJS?

I am currently working on a ReactJS project and I have come across an issue. I would like for the diacritic of a Devanagiri letter to be displayed in a different color than the letter it is attached to. For example: क + ी make की I was wondering ...

Unable to fetch the value for the property 'toString' as it is undefined

custom-filter.pipe.ts import { Pipe, PipeTransform } from '@angular/core'; @Pipe({ name: 'customFilter' }) export class CustomFilterPipe implements PipeTransform { transform(items: any[], searchTerm: string): any { if (!sear ...

Include a thousand separator and round to two decimal places in the ngModel input

I have been attempting to format my input values by adding thousand separators and 2 decimals as shown below TS onBlur(event){ if (event.target.value !== ''){ event.target.value = (parseFloat(event.target.value).toFixed(2)).toLocaleS ...

Trapped in the Google Maps labyrinth (Angular)

Hey there everyone! I'm currently working on an exciting angular application that integrates the Google Maps API. The goal is to create a feature that shows the 20 closest coffee shops based on the user's current location. However, I seem to be r ...

Annoying glitch when using http get in Ionic (version 3.19.0)

Issue: Having trouble with Ionic's http get function, as I keep running into this error message: Typescript Error Expected 1-2 arguments, but got 3. The line causing the problem seems to be similar to this: this.http.get('http://127.0.0.1 ...

`Developing reusable TypeScript code for both Node.js and Vue.js`

I'm struggling to figure out the solution for my current setup. Here are the details: Node.js 16.1.x Vue.js 3.x TypeScript 4.2.4 This is how my directory structure looks: Root (Node.js server) shared MySharedFile.ts ui (Vue.js code) MySharedFi ...

How can we effectively divide NGXS state into manageable sections while still allowing them to interact seamlessly with one another?

Background of the inquiry: I am in the process of developing a web assistant for the popular party game Mafia, and my objective is to store each individual game using NGXS. The GitLab repository for this project can be found here. The game includes the f ...

The system does not acknowledge 'NODE_OPTIONS' as a command that can be used internally or externally, or as an operational program or batch file

While trying to build my react + vite project, I encountered an error after running npm run build. https://i.stack.imgur.com/XfeBe.png Here is a snapshot of my package.json file. https://i.stack.imgur.com/MbbmY.png ...

Encountered difficulties when trying to incorporate SCSS into my rollup build

Desired Outcome I aim to develop a small library for personal use, focusing on separating code into library (product) and application (project) code. All my source code resides in the /src folder, consisting of React, TypeScript, and SCSS code. I would l ...

Attempting to send a POST request using a string as the payload via http.post

Struggling to make an http.post request from my Angular app to the rest server using this code: Using: import { Http } from '@angular/http'; let headers = new Headers(); headers.append('Content-Type', 'application/json'); ...

"Although TypeOrm successfully generates the database, there seems to be a connectivity issue

Attempting to set up a JWT authentication system using NestJs and SQLite. The code successfully generates the SQLite file, but then throws an error stating "Unable to connect to the database." Upon checking with the SQLite terminal, it became apparent that ...

NodeJs backend encounters undefined object due to FormData format request sent from Angular frontend

Never encountered this issue before despite having used this method for a long time. (Angular Frontend) const myFormData = new FormData(); myFormData.append("ok", "true"); this.http.put(my_Express_backend_url, myFormData); (Express ...

I'm curious about how to link a JSON field using dot notation in Angular 12 HTML

Does anyone know how to bind a JSON field using dot paths in Angular 12 HTML? For example: //Angular data: any = { name: 'x1', address: { city: 'xyz' } }; field: any = 'address.city'; //Html <input [(ngModel)]="data[ ...

The attribute specified is not present on the element within the array

I'm attempting to create an array that includes an object with initialized properties and a number. Yet, I encounter this error message: The error states: 'Property 'foo' does not exist on type 'number | IObj'. The proper ...

Angular does not display results when using InnerHtml

I'm currently in the process of creating a weather application with Angular, where I need to display different icons based on the weather data received. To achieve this functionality, I have developed a function that determines the appropriate icon to ...

Angular 6 introduces a new component with cascading comboboxes for easier data organization

In my Angular 6 project, I have successfully implemented a shared component called country-state. It is functioning perfectly. VIEW MY PERFECT WORKING EXAMPLE However, upon dividing the country-state component into separate country and state components, ...

The error form is not responding even after attempting to locate the issue

I have created a form and it was working fine, but now when I click on the submit or reset buttons, nothing happens. I've checked my code thoroughly line by line, but can't seem to find the issue. I even tried restoring previous versions, but no ...