AngularJS $ rootScope。$ broadcast在app.run中不起作用

AngularJS $ rootScope。$ broadcast在app.run中不起作用,第1张

AngularJS $ rootScope。$ broadcast在app.run中不起作用

你总是要有一个比赛条件。我可以选择几种替代方法:

1)使用服务。我并不是这个选项的忠实支持者,因为它会导致产生Spaghetti代码。大多数情况下,您不希望控制器在登录之前运行。我喜欢选项2。

 myApp.run(['AuthDataSvc', '$rootScope', function (AuthDataSvc, $rootScope) {        AuthDataSvc.getAuth(); }]);if(AuthDataSvc.isLoggedIn()){      //do something.}

2)使用route.resolve。解析是在路由上定义的,并且只有在将诺言设置为已解析后,Controller才会加载。我为您展示了一个示例

ui-router
ng-route
您需要选择毒药。如果您不使用
ui-router
,则应考虑使用。

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')    .controller('MyCtrl', ["UserToken", ... , function(UserToken){       //User Token will always be here when your Ctrl loads.   });

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


欢迎分享,转载请注明来源:内存溢出

原文地址: https://outofmemory.cn/zaji/5642131.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-12-16
下一篇 2022-12-16

发表评论

登录后才能评论

评论列表(0条)

保存