Problems arise with using the @ notation to access member functions in Coffeescript AngularJS service

For the sake of clarity, I've omitted some details.

I have implemented the User service using CoffeeScript's class system, but I am encountering issues when trying to access its own member functions.

User = (...) ->
    'ngInject'

    new class User

        constructor: ->
            @setRole() 

        login: (params) ->
            params.grant_type = 'password'

            request = {...}

            $http(request).then (response) ->
                $window.localStorage.token = response.data.access_token
                payload = jwtHelper.decodeToken(response.data.access_token)
                $rootScope.$broadcast EVENTS.AUTH.LOGIN
                @setRole() # PROBLEM LINE
            , (response) ->
                if response.status == 400
                    $rootScope.$broadcast EVENTS.ERROR.BAD_REQUEST
            ...

Whenever I try to call @setRole(), the browser reports that setRole() is undefined:

TypeError: Cannot read property 'setRole' of undefined

This translates to the following code:

  User = [..., function(...) {
    'ngInject';

    return new (User = (function() {
      function User() {
        this.setRole();
        console.log("User service loaded");
      }

      User.prototype.login = function(params) {
        var request;
        params.grant_type = 'password';
        request = {...}
        };
        return $http(request).then(function(response) {
          var payload;
          $window.localStorage.token = response.data.access_token;
          payload = jwtHelper.decodeToken(response.data.access_token);
          $rootScope.$broadcast(EVENTS.AUTH.LOGIN);
          return this.setRole(); # WRONG this, I PRESUME
        }, function(response) {
          if (response.status === 400) {
            return $rootScope.$broadcast(EVENTS.ERROR.BAD_REQUEST);
          }
        });
      };
      ...

My query is: why am I unable to invoke User.setRole() within my own service using the @ notation? Is there a workaround for this issue? I suspect it may be related to the mismatch between the this pointer and the User instance.

Answer №1

The issue arises when the `then` function is used, leading to a change in the context of `this`. To maintain consistency, opt for the fat arrow syntax (=>):

$http(request).then (response) =>

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

Exploring JSON parsing in AngularJS without running into reserved keywords

var jsonURL='../../json/xx.json' var myApp = angular.module('myApp',[]); myApp.controller('loaddata_traceroute', ['$scope','$http',function($scope, $http){ $http.get(jsonURL).success(function(data) { ...

Is there a way to configure json-server, when utilized as a module, to introduce delays in its responses

json-server provides a convenient way to introduce delays in responses through the command line: json-server --port 4000 --delay 1000 db.json However, when attempting to achieve the same delayed response using json-server as a module, the following code ...

Getting a list of connected users on a PeerJS server using Express is simple and straightforward. Follow these steps to

Trying to incorporate PeerJS, a webRTC library, into a game and utilizing their server for user discovery has proven challenging. The goal is to manage a list of connected users, but grappling with the PeerJS server has been difficult. The documentation s ...

Converting AngularJS breadcrumb within the StateProvider

I need to localize my breadcrumb elements in a specific way: url: moduls/1/question breadcrumb: Moduls -> Modul 1 -> Question The issue lies with the "Modul 1" section. My translation rule for this is "MODUL_TAG": "Modul {{short}}" breadcrumbtem ...

Regex fails to recognize repeated instances of a specific pattern

Currently, my goal is to create a JavaScript regex that can interpret instances of patterns like \123 and convert them into their corresponding ASCII values. For example, 65 should be replaced with A. If the backslash \ itself needs to be includ ...

I need to find a way to properly test a recursive, async JavaScript function by utilizing fake timers

I've been working with a basic recursive function that performs as expected when run. To thoroughly test its operation at each stage, I want to utilize Sinon's fake timers. Unfortunately, it seems that the fake timers are only affecting the init ...

utilizing regex to append a directory to the src attribute of all image tags

Hey there, I'm in need of a regular expression that can help me add an extra folder to all the image src paths. For example, changing assets/img/case-study/flyconnect/1.jpg to assets/img/case-study/flyconnect/big/1.jpg. Can anyone assist me with this? ...

What are some solutions for resolving an infinite loop of axios requests?

I am currently in the process of developing a web app for Spotify using its API. I have encountered an issue where the handleClick function in Albums.js is being called repeatedly when trying to make a get request for specific artist album data. Could this ...

`Count the number of rows needed to accommodate text line breaks within a div element`

Is there a method to determine the number of lines that text breaks into using the CSS property word-break: break-all? For example, if I have a div like this: <div>Sample text to check how many lines the text is broken into</div> And the corr ...

Connecting Angular Promises Together

I am currently facing an issue with chaining promises in Angular. My goal is to first fetch the project object from the API, then verify if the project owner has any containers. If containers exist, I want to trigger another GET request to retrieve the con ...

The rule 'react-hooks/exhaustive-deps' does not have a defined definition

I received an eslint error message after inserting // eslint-disable-next-line react-hooks/exhaustive-deps into my code. 8:14 error Rule 'react-hooks/exhaustive-deps' definition not found I tried to resolve this issue by referring to this p ...

Issue with refreshing the checkboxradio, it does not function properly when used with disabled preloaded fields

Displayed below are two checkboxes (one disabled and one not), both unchecked and disabled using JavaScript. However, the disabled checkbox does not function properly. Any solutions to this issue? function toggleProp(e, prop, selector) { var is = $(e) ...

What is the syntax for assigning a scope name like $scope.username.firstname in AngularJS?

Check out the snippet below This is a sample controller: angular.module("sampleApp").controller("transactionController",function($scope){ $scope.audit.lob = { "type": "select", "name": "Service", "value": "-S ...

How can I fix the 'Null is not an object' error that occurs while trying to assess the RNRandomBytes.seed function?

Currently, I am in the process of creating a mobile application using expo and react-native. One of the features I am working on involves generating a passphrase for users on a specific screen. To achieve this task, I have integrated the react-native-bip39 ...

Node.js refuses to launch - the dreaded error 404, signaling that it has mysteriously vanished

I am brand new to node.js, so please be patient with me as I learn. Currently, I am using the express framework and attempting to create a basic application that displays content as HTML. Below is the essentials of my app.js: var express = require(' ...

What are the best practices for utilizing environment variables within the public directory of a Next.js application

Hello there! I am currently working on a Next.js App. The app requires a custom service worker. I have incorporated push notifications using Firebase Cloud Messaging. But I prefer not to store environment variables in git. Currently, I am adding the fea ...

Angular app with regex patterns varying based on locale (decimal represented by dot or comma)

In my Angular 2 + PrimeNG application, I have a regular expression that validates numbers with floating point: <input pInputText pattern="[0-9]*\.[0-9]" [(ngModel)]="someModel"/> While this works fine for the US locale, some countries use a co ...

Looking to populate my HTML fields with values

When attempting to edit, the id is being passed but the data fails to populate in the HTML fields. Please refer to this image. Index @{ ViewBag.Title = "AngularJs Tutorial"; } <style> </style> <h2>AngularJs Tutorial : CRUD operatio ...

Is there a way to navigate to a different view in Ionic using $state.go without any transition effects?

I'm currently working on an Ionic application that utilizes a side menu. By default, the view transition animation slides from right to left. However, I need certain views to have no transition animation at all. I've searched through various do ...

When do you think the request is triggered if JSONP is essentially a dynamic script?

It appears that JSONP requests made using jQuery.ajax are not truly asynchronous, but rather utilize the Script DOM Element approach by adding a script tag to the page. This information was found on a discussion thread linked here: https://groups.google.co ...