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

Step-by-step guide on bypassing Content Security Policy with JavaScript

I have Content Security Policy enabled for security purposes in my current project, but I need to disable it for certain JavaScript files. Can this be done? I am trying to make API calls from my JavaScript files in order to retrieve results. ...

Problem with selecting dates in rangepicker

Having trouble with my recursion code for selecting dates in a rangepicker: recurse( () => cy.get('.mantine-DatePicker-yearsListCell').invoke('text'), (n) => { if (!n.includes(year)) { //if year not f ...

Angular 6 Universal does not pause for resolver completion

I recently completed the installation of Angular Universal start kit version 6 and designed my component within it. The main purpose of this component is to retrieve user information from an API upon loading and display it on the view. The issue I am faci ...

Steps to create a personalized loading screen using Angular

I am looking to enhance the loading screen for our angular 9 application. Currently, we are utilizing <div [ngClass]="isLoading ? 'loading' : ''> in each component along with the isloading: boolean variable. Whenever an API ...

How can we make type assertions consistent without sacrificing brevity?

In the project I am currently working on, we have implemented a warning for typescript-eslint/consistent-type-assertions with specific options set to { assertionStyle: 'as', objectLiteralTypeAssertions: 'never' }. While I generally appr ...

The default settings for the Nebular corporate theme do not function as expected

After setting up a project with ng new and adding nebular to an existing app following the instructions, I defaulted to cosmic which resulted in certain files being generated. When I try to set the theme to 'corporate' in NbThemeModule.forRoot(), ...

"Encountering a Server Error when attempting to refresh routing children

My project is hosted on a subDirectory server with Apache. The base index for my project can either be <base href="./"> or <base href="/myFolder/">. The issue arises when I am on a child route page, for example: www.mysite ...

Angular - the ngFor directive causing function to be executed repeatedly

I need help with a template: <mat-card *ngFor="let cargo of cargos" class="cont-mat"> ... <mat-checkbox *ngFor="let truck of (retrievingTrucksByUserIdAndRules(cargo.id) | async)" formControlName="truckId" ...

The InAppBrowser seems to have trouble loading pages with cookies when I attempt to navigate back using the hardware back button

In my Ionic/Angular application, I utilize the InAppBrowser plugin to access a web application for my company. The InAppBrowser generally functions properly; however, there is an issue with a cookie within the web application that controls filters for cert ...

Need to import a JSON file and convert it to an interface in order to ensure that all fields are included

I am facing an issue where I am attempting to parse a json file using require(). My goal is to convert it into a specific data type and have the conversion fail if the file does not contain all the necessary fields as defined by the interface. Below is my ...

Varieties of data classifications for the information obtained from supabase

1 I'm encountering an issue while attempting to define the data types from Supabase. I received an error message stating: "type '{ id: string; title: string; capacity: number | null; start_date: Date | null; start_time: string | null; end_ ...

Generics-based conditional type that verifies entry properties

I developed a function that accepts an argument with two different architectures. I intentionally avoided enforcing rules to allow flexibility for the user, which is now causing me some headaches ...

What is the correct way to nest multiple ng-if statements?

I'm currently grappling with a problem involving multiple nested ngIf directives applied to ng-template elements in Angular.js, and I've yet to find the ideal solution. While I am aware of workarounds, they are not as efficient as I would like th ...

The 'books' property cannot be found on the 'client' type

I am currently integrating the Google Book API into my project and encountering an issue while trying to add a book to a library using gapi.client. The error I keep receiving is as follows: This is the request : gapi.client.books.mylibrary.bookshelves.volu ...

Typescript - Creating a Class with Constructor that Extends an Interface without Constructor

I am faced with an interface structured as follows: interface Person { id: number name: string } In my implementation class for this interface, I have the following code: class PersonClass implements Person { id: number = 123 name: string = &apo ...

Troubleshooting the NullInjectorError in Angular - Service Provider Missing?

I'm facing an issue in my code where I have buttons that should trigger pop-ups displaying details as a list when clicked. However, every time I click the buttons, I encounter the error mentioned below. It seems like I am unable to access the desired ...

Avoid accessing members in Vue 3 using TypeScript that may be unsafe

Recently, we initiated the process of upgrading from Quasar v1 to Quasar v2 (moving from Vue 2 to Vue 3). In the past, this code functioned without any issues: // src/pages/myComponent.vue <script lang="ts"> import { defineComponent } from ...

Encountering an Eslint issue: "Function missing return type" while adding a styled component to _document.tsx in Next.js

Setting up my NextJS project with styled components and Typescript has been my current focus. After consulting the official NextJS documentation, I successfully configured the _document.tsx file, which appears like this: import Document, { DocumentContext ...

What is the best way to list the choices associated with a specific category?

The Node.js package I'm currently working with requires an argument of a specific type, which I can see is defined through a TypeScript declaration as follows: export declare type ArgType = 'A' | 'B' | 'C'; I am interes ...

The issue is that TypeScript is indicating that the type 'string | string[]' cannot be assigned to the type 'string'

I recently upgraded to Angular 16 and encountered an issue with an @Input() property of type string | string[]. Prior to the upgrade, everything was functioning correctly, but now I am experiencing errors. I am uncertain about where I may have gone wrong i ...