Caleb Faruki
Caleb Faruki

Reputation: 2735

Coffeescript AngularJS service, can't access member functions using @ notation

I've removed some stuff for legibility.

I've written the User service using the CoffeeScript class system, but it is giving me problems when it attempts 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
            ...

When I attempt to invoke @setRole(), the browser informs me that setRole() doesn't exist:

TypeError: Cannot read property 'setRole' of undefined

This compiles to this:

  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 question is: why am I not able to invoke User.setRole() within my own service, using @ notation? Is there a workaround for this? I presume it has something to do with the this pointer not corresponding to the User instance.

Upvotes: 1

Views: 63

Answers (1)

Jordão
Jordão

Reputation: 56497

The problem is that in the function you pass to then, this changes. To keep it the same, use the fat arrow syntax (=>):

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

Upvotes: 1

Related Questions