Struggling to access the `this` keyword within a callback function in an Angular Controller class using ES

Take a look at this sample class:

class LoginController{
    constructor(authService,$timeout,$state){
        let vm = this;
        this.loading = false;
        this._authService = authService;
        this._$timeout = $timeout;
        this._$state = $state;
        this.loading = false;
        this.statusMessage = null;
    }

    login(){
        this.loading = true;
        this.statusMessage = null;

        let loginModel = {
            UserName : this.username,
            Password : this.password,
            RememberMe : this.rememberMe
        };

        //Login User
        this._authService.login(loginModel).then(function(user){
            //Set User Login & send to Dashboard
            this._authService.setUser(user);
            this._$state.go("dashboard");

        }, function(error){
            const errorMessage = error ? error.Message : "Undefined Login Issue occurred !";
            this.loading = false;
        });
    }
}

All is functioning as expected, except for when the error callback function triggers and reaches this.loading = false; resulting in an "undefined" error.

Is there a way to maintain a reference to the Class "this" within the error callback?

Answer №1

To maintain the scope, fat arrows must be used.

//Authenticate User
this._authService.authenticate(authModel).then((user) => {
    //Set User Authentication & redirect to Dashboard
    this._authService.setUser(user);
    this._$state.go("dashboard");
}, (error) => {
    const errorMessage = error ? error.Message : "An undefined authentication issue occurred!";
    this.loading = false;
});

Answer №2

This issue arises frequently when passing context to a callback function. One common solution is to define something similar to

var me=this; in the scope where you need to maintain "this" and then access it in your callback function like this

function myCallback () {
    me.myvariable=true;
};

In your specific scenario, you have already initialized let vm = this; so you can utilize

vm._authService.setUser(user);
vm._$state.go("dashboard");

Answer №3

function(error){
    this.loading = false;
}

The function's scope changes the reference of 'this' to itself instead of the parent function.

To address this issue, create an alias for 'this':

class LoginController{
    constructor(authService,$timeout,$state){
        let vm = this;
        this.loading = false;
        this._authService = authService;
        this._$timeout = $timeout;
        this._$state = $state;
        this.loading = false;
        this.statusMessage = null;
    }

    login(){
        var self = this; //Create an alias for 'this'

        this.loading = true;
        this.statusMessage = null;

        let loginModel = {
            UserName : this.username,
            Password : this.password,
            RememberMe : this.rememberMe
        };

        //Login User
        this._authService.login(loginModel).then(function(user){
           //Set User Login & send to Dashboard
            self._authService.setUser(user);
            self._$state.go("dashboard");

        }, function(error){
            const errorMessage = error ? error.Message : "Undefined Login Issue occurred !";
            self.loading = false; //Self refers to this of parent scope
        });
    }
}

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

Struggling to integrate Karma and Jasmine into my Angular controller setup

After numerous attempts and hours of troubleshooting, I am still unable to successfully integrate Karma with my Angular controller. No matter what I try, the same error persists even when removing expectGET() calls - as soon as $http.flush(); is called. A ...

Next.js allows you to create a single page that corresponds to the root path '/' as well as a dynamic route '/param'

I have a single-page website built with Next.js. The home page, which displays a list of products, is located at route / and the corresponding code can be found in pages/index.js. Each product has an id, allowing users to jump directly to it using /#produc ...

Error encountered when attempting to initiate a second screenshare on Chrome due to an invalid state

I am interested in utilizing Screensharing in Chrome. After following a guide and creating an extension to access the deviceId for getUserMedia, I was able to successfully start streaming my screen. However, when I attempted to stop the stream using the pr ...

Why does my loading screen appear again when I submit the form and refresh the page?

I've been working on setting up a login page and was able to create a loading screen that fades away once the page has finished loading. $(window).on("load",function(){ setTimeout(function() { $(".lo ...

Would it be appropriate to use require("fs") instead of require("node:fs") as a workaround in the OpenAI package?

I have inherited a project and am currently integrating OpenAI into it. Initially, I was informed to use Node 16, but after consulting with other developers on the project, I discovered that everyone is actually using version 14.17.3. The OpenAI package c ...

What steps can be taken to identify the script responsible for preventing text highlighting or right clicking on a webpage?

Whenever I visit aliexpress using Chrome, I encounter issues where I am unable to highlight text on an item's page (although it works fine on the search results list) and cannot right-click to access the context menu on images. Both of these functions ...

Concealing the rear navigation button within the material carousel

I have a material css carousel, and I am trying to hide the back button on the first slide. I attempted to use the code below from a previous post The following code snippet prevents the user from looping through the carousel indefinitely. Stop looping i ...

Cryptocurrency price tracker with sleek Bitcoin symbol and FontAwesome icons

My assignment involved creating a function that retrieves Bitcoin trades from a JSON URL, allows users to change the interval with buttons, uses fontawesome arrows to indicate rate changes (up/down/no change), and displays the data on a website. Everythin ...

Looking for a simple method to convert JSON object properties into an array?

Is there a simple method for extracting only the values of the properties within the results object in the given JSON data? let jsonData = {"success":true, "msg":["Clutch successfully updated."], "results":{"count_id":2, ...

What methods can I use in JavaScript to convert a string into a hash, and then retrieve the original string from

I need to find a way to include a very long string (~70,000 characters) in a URL. It is important for me to have the ability to implement back-forward functionality in a browser so that my application can respond and adjust its state when the URL changes. ...

Retrieving dynamically generated form components upon submission in a React application

I am facing an issue with a modal containing a dynamically rendered form in my React component. I want to gather all the user-entered field values and send them to the backend. Below is the code for rendering the dynamic form fields: import React from &ap ...

Using jQuery to send data with an AJAX post request when submitting a form with

This is the code I'm working with: <html> <body> <?php include('header.php'); ?> <div class="page_rank"> <form name="search" id="searchForm" method="post"> <span class="my_up_text">ENTER THE WEBSITE TO ...

Initiating PHP outcomes with the integration of JQUERY and Bootstrap

Currently, I am working on a Twitter search functionality that allows me to search for any content on Twitter. While the feature is functional, I am facing some challenges with displaying the results in the desired format. Ideally, I would like the results ...

Send a request to templateUrl

After experimenting with AngularJS, I decided to create a dynamic route system that funnels all routes through a single PHP file. This was motivated by my desire to prevent users from accessing raw templateUrl files and seeing unstyled partial pages. Prio ...

Having trouble administering $httpBackend injection

Currently, I am utilizing Angular 1.5 to create mocked services for my current project by referring to this helpful example: https://embed.plnkr.co/qsmx8RUmQlXKkeXny7Rx/ Here is a snippet of the code that I have developed so far: function() { 'use ...

AngularJS sending unsupported media type to SpringMVC controller

Encountering an error while attempting to post JSON data from an AngularJS controller to a SpringMVC controller. Despite trying various solutions found online and ensuring that the jackson library is in the classpath, the issue persists. It's worth no ...

What is the best way to obtain a list of all the modules that are currently accessible in AngularJS

When declaring an Angular module, I specify its dependencies as follows: const myModule = angular.module("MyModuleName", ["Dep1", "Dep2", "Dep3"]); Each dependency comes with its own set of dependencies, directives, controllers, etc. Is there a way to qu ...

Tips for verifying login credentials with MongoDB and Express: Leveraging db.collection().findOne() or .find() functions

I am encountering an issue with a POST request involving user credentials being sent from a Login page to the API Server. The code looks like this: loginUser(creds) { //creds is in the form of { username: bob, password: 123 } var request = { ...

JavaScript is experiencing an error where it cannot define a function, rendering it unable to generate a JSON object due to its inability to recognize that the

I've created a JavaScript script function that holds cart items for ordering food. This function takes two parameters: ID and price. Here is a snippet of my script file: <script> function addtocart(mitem, mprice) { var price = ...

I am looking to adjust/modulate my x-axis labels in c3 js

(I'm specifically using c3.js, but I also added d3.js tags) I have been working on creating a graph that displays data for each month based on user clicks. However, I am facing an issue where the x-axis labels show 0-X instead of 1-X. For instance, ...