Using TypeScript to call a class method from within another function

Currently, I am working on an Angular 2 application and struggling to grasp the concept of TypeScript's this scope.

Within my TypeScript class named SharedService, there is a function called handleError. If this function encounters a 401 status, I want it to trigger another function called logout(), which is also within the same class.

I have read that in order to successfully utilize functions alongside this, I should define them using arrow function syntax, just like in the example below. However, despite implementing this suggestion, I keep getting the following error:

TypeError: this.logout is not a function(…)

Could anyone provide insights into what mistake I might be making?

export class SharedService {

    logout = () => {
      console.log('Logout.');
    }

    //This method catches any errors that might arise upon http requests
    handleError(error: any) {
        if (error.status === 401) {
          this.logout(); <----------------------------- This returns the error
        }
        console.error(errMsg); // log to console instead
    }
}

The issue occurs specifically when attempting to call this.logout().

Answer №1

Utilize .bind(this)

logout() {
  ...
  return this._http.delete(url, options)
        .map(res => res)
        .catch(this.handleError.bind(this));

Alternatively, you can use arrow functions

logout() {
  ...
  return this._http.delete(url, options)
        .map(res => res)
        .catch((err) => this.handleError(err));

In this scenario, one drawback is that the parameters must be repeated with =>, unlike with .bind(this). When the callback is defined inline, () => is often more convenient.

Answer №2

Absolutely. The reason for this behavior is due to typescript converting the logout function into a SharedService function.

Here's an example:

function SharedService() {
    var _this = this;
    this.logout = function () {
        console.log('Logout.');
        var headers = new Headers({ 'Content-Type': 'application/x-www-form-urlencoded' });
        var options = new RequestOptions({ headers: headers });
        var url = API_URL + 'users/sign_out.json';
        return _this._http.delete(url, options)
            .map(function (res) { return res; })
            .catch(_this.handleError);
    };
}

The handleError function is attached to the prototype like so:

//This method catches any errors that might arise upon http requests
SharedService.prototype.handleError = function (error) {
    if (error.status === 401) {
        this.logout();
    }
    var errMsg = (error.message) ? error.message :
        error.status ? error.status + " - " + error.statusText : 'Server error';
    console.error(errMsg); // log to console instead
    return Observable.throw(errMsg);
};

In addition, the scope of this has been changed to another one.

To handle this situation, you will need to use:

.catch(() => this.handleError);

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

What is the process for linking my component to my socket.io server?

I am facing a challenge in setting up a socket.io server to facilitate communication between two components: a command interface for sending data, and an overlay component for receiving it. Below is the code snippet: interface.component.html : <input ...

Unable to pass parameters through the URL in Angular's POST request

Hey there! I'm currently facing an issue with passing a parameter in the POST method URL within an Angular service to construct a URL for fetching data from an API. However, when I try calling it in the component file, I keep getting an error response ...

What is the best way to convert the text on a button into another language?

Currently, I am facing an issue with translating a button using Angular. The translation appears to be outside of the button in question. Additionally, there is another problem that I have encountered. For reference, here is a sample: https://i.stack.i ...

What is the abbreviation for indicating a return type as nullable?

Is there a way to use shorthand for nullable return types in TypeScript similar to using "name?: type" for parameters? function veryUsefulFunction(val?: string /* this is OK */) // but not this or other things I've tried. // is there a way a ...

Is it possible to provide unrestricted support for an infinite number of parameters in the typing of the extend function from Lodash

I am utilizing the "extend" function from lodash to combine the objects in the arguments as follows: import { extend } from 'lodash'; const foo1 = { item: 1 }; const foo2 = { item: 1 }; const foo3 = { item: 1 }; const foo4 = { item: 1 }; const f ...

I have a Visual Studio 2019 solution that consists of two projects - one is an Angular project and the other is written in TypeScript. I have successfully configured

We are currently utilizing Visual Studio 2019 (not the VS Code version) for our project. Within this solution, we have multiple projects included. One of these projects contains Angular code that we compile using the traditional 'ng build' comma ...

NextJS and Context API throwing a Typescript error

I've been working on my _app.tsx file and here's the code snippet I have: import React from 'react' import type { AppProps } from 'next/app' /* Import Styles */ import '@themes/index.scss' /* Import Template */ imp ...

Chakra UI - The "Open Modal" button is disabled from being clicked repeatedly

Encountering an issue with Chakra UI modal dialog in Next.js. Attempting to utilize the code below in pages/index.tsx for displaying a modal dialog. import type { NextPage } from "next"; import { Modal, ModalOverlay, ModalContent, Moda ...

Passing a click event to a reusable component in Angular 2 for enhanced functionality

I am currently working on abstracting out a table that is used by several components. While most of my dynamic table population needs have been met, I am facing a challenge with making the rows clickable in one instance of the table. Previously, I simply ...

What is the best way to place a p-growl element in the bottom right corner of the page?

I've been struggling to fix the positioning of my growl message at the bottom right corner by overriding the CSS classes of p-growl. Initially, I attempted to override the .ui-growl class like this: ::ng-deep .ui-growl { position: fixed; b ...

Troubleshooting Issue: Data not appearing on Angular frontend when fetching from Laravel API

Utilizing Laravel for the back end and Angular for the front end development. The code segments related to Angular can be found in employee.component.ts file: import { Component, OnInit } from '@angular/core'; import { DataService } from 'sr ...

Tips for obtaining type narrowing for a function within a mixed array

In my coding adventure, I have crafted a brilliant match function. This function is designed to take a value along with an array of [case, func] pairs. The value is then compared to each case, and if a match is found, the associated func is executed with t ...

Is it possible to utilize [(ngModel)] in all components when including FormsModule in the app.module.ts file?

Is it possible to utilize [(ngModel)] in every component after importing FormsModule in app.module.ts? In app.module.ts import { FormsModule } from '@angular/forms'; Implementing in another component In view.component.html input type="text" ...

Tackling the white-source security problem in npm libraries

A security advisory from White-source has identified high vulnerability issues with certain libraries used in your repository, specifically with yargs-parser: 1. build-angular-0.13.8.tgz (Root Library) node-sass-4.11.0.tgz sass-graph-2.2 ...

Tips for customizing the appearance of a label when a MUI Radio Button is selected

Hello everyone, I am attempting to customize the label text color of a radio button to turn blue when selected. https://i.stack.imgur.com/btSc2.jpg HERE IS THE CODE FOR MY MUI BUTTON SO FAR import * as React from "react"; import Radio from &quo ...

Vercel deployment encountered an AxiosError with a status code of 404

I am currently working on an API route called app/api/posts/route.ts, which is responsible for fetching all posts from my database using Prisma ORM. In the localhost environment, the database is hosted on my local PostgreSQL server. However, in production, ...

What is causing elements like divs, paragraphs, or text not to display within an ion-item after an ion-input is added?

I am currently working on validating a simple form and everything seems to be functioning properly. However, I have encountered an issue with displaying text messages within an ionic 3 list item. The ion-item consists of an ion-input element. When I place ...

Is there a way to use openapi-generator with typescript-angular to generate just a module within an existing Angular project instead of creating a separate package?

Currently, I am utilizing the openapi-generator tool specifically for typescript-angular. Although I have been able to successfully generate an Angular module along with all its components, it results in a separate npm package. While I acknowledge the ad ...

Running JavaScript code when the route changes in Angular 6

Currently, I am in the process of upgrading a website that was originally developed using vanilla JS and JQuery to a new UI built with Angular and typescript. Our site also utilizes piwik for monitoring client activity, and the piwik module was created i ...

What are some ways to get Angular2 up and running in a newly created distribution directory?

Trying to setup my own Angular2+Typescript (+SystemJS+Gulp4) starter project has hit a roadblock for me. I encountered issues when transitioning from compiling TypeScript in the same folder as JavaScript with access to the node_modules folder, to organizin ...