Mateus
Mateus

Reputation: 9

Can't update vars inside Angularjs Factory

Anyone can help with this? Can't update var ABCKey. Execute setAuthenticatedAccount and console.log return correct value. After that, run getAuthenticatedAccount, and receive undefined.

angular.module('authentication.service', [
])

.factory('Authentication', ['$state', '$cookies', '$http', 'app', 'routes', 'cfCryptoHttpInterceptor',
    function($state, $cookies, $http, app, routes, cfCryptoHttpInterceptor) {

    var ABCKey;

    var setAuthenticatedAccount = function (account, tokenAuth) {
        var accountInfo = {'email': account.email, 'username': account.username, 'token': tokenAuth}
        var abc = CryptoJS.enc.Base64.parse(account.abc);

        Authentication.setABCKey(abc);

        console.log(Authentication.showABCKey())

    }

    var getAuthenticatedAccount = function() {
        if(!$cookies.authenticatedAccount) {
            return;
        }

        console.log(Authentication.showABCKey())

    }


    var setABCKey = function(key) {
        ABCKey = key;
    };

    var showABCKey = function() {
        return ABCKey;
    };

    var Authentication = {
        setAuthenticatedAccount: setAuthenticatedAccount,
        getAuthenticatedAccount: getAuthenticatedAccount,
        setABCKey: setABCKey,
        showABCKey: showABCKey 
    };

    return Authentication;
}]);

Upvotes: 0

Views: 52

Answers (2)

Shailendra Singh Deol
Shailendra Singh Deol

Reputation: 637

Remove Authentication while you are calling your functions because it is creating object every time. And also set var ABCKey=null at the time of decelaration like this-

angular.module('authentication.service', [
])

.factory('Authentication', ['$state', '$cookies', '$http', 'app', 'routes', 'cfCryptoHttpInterceptor',
    function($state, $cookies, $http, app, routes, cfCryptoHttpInterceptor) {

    var ABCKey=null;

    var setAuthenticatedAccount = function (account, tokenAuth) {
        var accountInfo = {'email': account.email, 'username': account.username, 'token': tokenAuth}
        var abc = CryptoJS.enc.Base64.parse(account.abc);

        setABCKey(abc);

        console.log(showABCKey())

    }

    var getAuthenticatedAccount = function() {
        if(!$cookies.authenticatedAccount) {
            return;
        }

        console.log(showABCKey())

    }


    var setABCKey = function(key) {
        ABCKey = key;
    };

    var showABCKey = function() {
        return ABCKey;
    };

    var Authentication = {
        setAuthenticatedAccount: setAuthenticatedAccount,
        getAuthenticatedAccount: getAuthenticatedAccount,
        setABCKey: setABCKey,
        showABCKey: showABCKey 
    };

    return Authentication;
}]);

Upvotes: 2

Sumit Jaiswal
Sumit Jaiswal

Reputation: 857

dont use var its single tone class you need to define ABCkey in this

var ABCKey;

try with this

this.ABCKey = '';

Upvotes: 0

Related Questions