2016-02-27 156 views
3

我有一個工廠返回3個函數:setToken,getToken,isAuthenticated。前兩個函數是預定義的,最後一個函數調用getToken函數,使用this.getToken錯誤:this.getToken不是函數

將工廠注入控制器時,然後使用ng-show調用第三個函數(isAuthenticated())。我的控制檯出現以下錯誤:

Error: this.getToken is not a function
[email protected]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> 

如果你覺得缺少任何東西或需要更多信息,請詢問我將其添加到問題中。

+0

嘗試緩存此; var me = this; return !! me.getToken(); – Akis

+0

仍然返回相同的錯誤 - 錯誤:me.getToken不是一個函數 –

+0

你在哪裏聲明var me = this; ? – Akis

回答

2

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

});