Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Error: this.getToken is not a function

I have a factory that returns 3 functions: setToken, getToken, isAuthenticated. The first two functions are predefined, and the last one calls the getToken function, using this.getToken.

When injecting the factory into the controller, I then call the third function (isAuthenticated()), using ng-show. I get the following error in my console:

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

Can anybody help me with what I'm doing wrong?

The factory:

'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();
    }
  };

});

The Controller:

'use strict';

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

The View:

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

If you feel that anything is missing or need more information, please ask and I'll add it to the question.

like image 680
Miha Šušteršič Avatar asked Mar 03 '26 14:03

Miha Šušteršič


1 Answers

getToken is a static method of the object you are exposing in the factory, so you can't refer to it with this. You can however do something like 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
  };

});
like image 120
Nhor Avatar answered Mar 06 '26 04:03

Nhor



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!