【问题标题】:share factory value between different modules在不同模块之间共享工厂值
【发布时间】:2016-07-26 16:01:04
【问题描述】:

我对 angularjs 很陌生,我有三个模块和一个工厂。我想在不同模块之间共享工厂的价值。我不知道我做错了什么,因为在运行中,在调用登录后 userRole 不会更新。

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

【问题讨论】:

  • 通过 plunker 、 html 和 js 文件共享您的代码?

标签: angularjs factory


【解决方案1】:

您的问题在于以下几行:

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

要么消除angular.module("main", []),要么将其更改为angular.module("main")。注意没有第二个参数。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-02-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-04-20
    相关资源
    最近更新 更多