AngularJS$rootScope.$broadcast在app.run中不工作

AngularJS$rootScope.$broadcast在app.run中不工作,angularjs,Angularjs,我在AngularJS.run下有以下代码,它在我的本地开发机器上运行得很好,但在上传到我的客户端服务器时无法工作……经过几次测试后,很明显,在加载控制器时,事件尚未触发,因此控制器中依赖于此事件的大多数功能都无法工作。有人能告诉我我做错了什么,以及如何修复它吗?谢谢 myApp.run(['AuthDataSvc', '$rootScope', function (AuthDataSvc, $rootScope) { AuthDataSvc.getAuth().then(fun

我在AngularJS.run下有以下代码,它在我的本地开发机器上运行得很好,但在上传到我的客户端服务器时无法工作……经过几次测试后,很明显,在加载控制器时,事件尚未触发,因此控制器中依赖于此事件的大多数功能都无法工作。有人能告诉我我做错了什么,以及如何修复它吗?谢谢

myApp.run(['AuthDataSvc', '$rootScope', function (AuthDataSvc, $rootScope) {    
    AuthDataSvc.getAuth().then(function(Token){
        $rootScope.$broadcast('Token', Token);
    }, function(status){
        console.log(status);
    });     
}]);

你总是会有一个比赛状态。我有几个选择,你可以做:

1) 使用服务。我不是这个选项的真正粉丝,因为它会导致意大利面代码。大多数情况下,在登录之前,您不希望控制器运行。我更喜欢选择2

 myApp.run(['AuthDataSvc', '$rootScope', function (AuthDataSvc, $rootScope) {    
    AuthDataSvc.getAuth(); /* no op we will use the service to determine logged in */
}]);


/* inside a controller */
if(AuthDataSvc.isLoggedIn()){
      //do something.
}

2) 使用一个。解析是在路由上定义的,控制器将仅在承诺设置为解析后加载它。我向您展示了
ui路由器
ng路由
的示例,您需要选择毒药。如果你不使用,你应该考虑它。
/* app.config ... route config.. */
var waitForLogon = {
      UserToken: ["AuthDataSvc", function (AuthDataSvc) {
         return AuthDataSvc.logon();
      }]
};

//this is for ng-route
 $routeProvider
   .when('/Book/:bookId', {
      templateUrl: '--',
      controller: 'MyCtrl',
      resolve: waitForLogon
   })


//this is for ui-router 
$stateProvider
     .state('me', {
            templateUrl: '--',
            controller: 'MeCtrl',
            resolve: waitForLogon
 })


/*服务代码--*/
angular.module('yourapp')
.service('AuthDataSvc',[“LogonModel”,“$q”,函数(LogonModel,$q){
这个。_q=null;
var=这个;
这是。_doAuth=function(){
this.getAuth().then(函数(令牌){that.q.resolve(令牌)},函数(error){that.q.reject(error);}
};
this.logon=函数(){
如果(!这个){
这个。_q=$q.defer();
这个//
/* controller */
 angular.module('yourapp')
    .controller('MyCtrl', ["UserToken", ... , function(UserToken){
                  //User Token will always be here when your Ctrl loads.
   });
/* service code -- */
angular.module('yourapp')
    .service('AuthDataSvc', ["LogonModel", "$q", function(LogonModel, $q) {
        this._q = null;
        var that = this;
        this._doAuth = function(){
           this.getAuth().then(function(Token){ that._q.resolve(Token) }, function(error){that._q.reject(error);}
        };
        this.logon = function () {
            if(!this._q){
              this._q = $q.defer();
               this._doAuth();// <-current auth do here, and resolve this._q when done
            }
            return this._q.promise;
        };
    });