Error: this.getToken is not a function

Error: this.getToken is not a function

我有一个工厂 returns 有 3 个功能:setTokengetTokenisAuthenticated。前两个函数是预定义的,最后一个调用getToken函数,使用this.getToken.

将工厂注入控制器时,我使用 ng-show 调用第三个函数 (isAuthenticated())。我的控制台出现以下错误:

Error: this.getToken is not a function
.isAuthenticated@http://localhost:9000/scripts/services/authtoken.js:22:16

任何人都可以帮助我解决我做错的事情吗?

工厂:

'use strict';

angular.module('psJwtApp').factory('authToken', function($window) {
  //define storage
  var storage = $window.localStorage;
  var cachedToken;

  // Public API here
  return {
    setToken: function(token) {
      cachedToken = token;
      storage.setItem('userToken', token);
    },
    getToken: function() {
      if (!cachedToken) {
        cachedToken = storage.getItem('userToken');
      }
      return cachedToken;
    },
    isAuthenticated: function() {
      //return true if we get something from getToken
      return !!this.getToken();
    }
  };

});

控制器:

'use strict';

angular.module('psJwtApp').controller('HeaderCtrl', function($scope, authToken) {
    $scope.isAuthenticated = authToken.isAuthenticated;
});

视图:

  <ul class="nav navbar-nav">
    <li ui-sref-active="active">
      <a ui-sref="main">Home</a>
    </li>
    <li ng-hide="isAuthenticated()" ui-sref-active="active">
      <a ui-sref="register">Register</a>
    </li>
    <li ng-show="isAuthenticated()" ui-sref-active="active">
      <a ui-sref="logout">Logout</a>
    </li>
  </ul>

如果您觉得缺少任何内容或需要更多信息,请询问,我会将其添加到问题中。

getToken是你在工厂中公开的对象的静态方法,所以你不能用this引用它。但是你可以这样做:

'use strict';

angular.module('psJwtApp').factory('authToken', function($window) {
  //define storage
  var storage = $window.localStorage;
  var cachedToken;

  var setToken = function(token) {
    cachedToken = token;
    storage.setItem('userToken', token);
  };
  var getToken = function() {
    if (!cachedToken) {
      cachedToken = storage.getItem('userToken');
    }
    return cachedToken;
  };
  var isAuthenticated = function() {
    //return true if we get something from getToken
    return !!getToken();
  };

  // Public API here
  return {
    setToken: setToken,
    getToken: getToken,
    isAuthenticated: isAuthenticated
  };

});