我在AngularJS .run下有以下代码,该代码在我的本地开发计算机上可以正常运行,但在上传到客户端服务器后将无法工作...经过几次测试,很明显,在加载控制器时,事件并未尚未触发,因此取决于此事件的控制器中的大多数功能均无法正常工作。有人可以告诉我我在做什么错以及如何解决吗?谢谢
myApp.run(['AuthDataSvc', '$rootScope', function (AuthDataSvc, $rootScope) {
AuthDataSvc.getAuth().then(function(Token){
$rootScope.$broadcast('Token', Token);
}, function(status){
console.log(status);
});
}]);
最佳答案
你总是要有一个比赛条件。我可以选择几种替代方法:
1)使用服务。我并不是这个选项的忠实支持者,因为它会导致产生Spaghetti代码。大多数情况下,您不希望控制器在登录之前运行。我喜欢选项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)使用route.resolve。解析是在路由上定义的,并且只有在将诺言设置为已解析后,Controller才会加载。我为您展示了
ui-router
和ng-route
的示例,您需要选择毒药。如果不使用ui-router
,则应考虑使用。/* 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
})
/* 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;
};
});