简体   繁体   中英

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.

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) =>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM