栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

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

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

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


转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/636271.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号