简体   繁体   English

Coffeescript AngularJS 服务,无法使用@ 符号访问成员函数

[英]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.我已经使用 CoffeeScript 类系统编写了 User 服务,但是当它尝试访问自己的成员函数时给我带来了问题。

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:当我尝试调用@setRole() ,浏览器通知我 setRole() 不存在:

TypeError: Cannot read property 'setRole' of undefined类型错误:无法读取未定义的属性“setRole”

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?我的问题是:为什么我不能在我自己的服务中使用@符号调用 User.setRole()? Is there a workaround for this?有解决方法吗? I presume it has something to do with the this pointer not corresponding to the User instance.我认为它与不对应于 User 实例的 this 指针有关。

The problem is that in the function you pass to then , this changes.问题是在您传递给then的函数中, this发生变化。 To keep it the same, use the fat arrow syntax ( => ):为了保持不变,请使用粗箭头语法( => ):

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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