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.
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
};
});
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.