liss.sb
liss.sb

Reputation: 351

share factory value between different modules

I am very new with angularjs, I have three modules and a factory. and I want to share the values of the factory between the different modules. I do not know what I am doing wrong, because in the run the userRole does not update after the login has been call.

angular.module("main", ["app", "controller"])
angular.module("main", [])
.factory("authService", authService);

function authService(){
    var userRole =  "",
    service = {
        setRole : setRole,
        getRole : getRole
    };
    return service
    function setRole(role){
        userRole = role;
    }
    function getRole(){
        return userRole;
    }
}



angular.module("controller", [])
.controller("Controller1", Controller)

Controller.$inject = ["authService"]

function Controller(authService){
   afterCallLogin().then(data, function(){
     authService.setRole(data.role);
     console.log(authService.getRole()) // this print "user" **CORRECT**
  });
}




angular.module('app', [])
.run('runApp', runApp);

runApp.$inject = ['$rootScope', '$state', '$stateParams', 'authService']
function runApp($rootScope, $state, $stateParams, authService){

$rootScope.$on('$stateChangeStart', function(event, toState, toParams,  fromState, fromParams) {
  console.log(authService.getRole()) // this print an empty value, **DOES NOT CHANGE**
  });
}

Upvotes: 2

Views: 136

Answers (1)

Lex
Lex

Reputation: 7204

Your issue is with these lines:

angular.module("main", ["app", "controller"])
angular.module("main", [])
.factory("authService", authService);

Either eliminate the angular.module("main", []) or change it to angular.module("main"). Notice the absence of the second parameter.

Upvotes: 2

Related Questions