项目重要实现一个功能,从后端接口中获取用户信息(userInfo)要在整个应用中保持值,在directive中使用,于是就在run方法中这样写
app.run(['$rootScope', 'baseHttpService', function ($rootScope, baseHttpService) {
//获取当前登录人用户名
baseHttpService.doGet(null, path.system.currentUser).then(data => {
$rootScope.userInfo = data.data;
});
}]);
baseHttpService是应用中封装的http请求,就相当于$http()。
run方法是肯定要先于directive()方法执行的,但由于http是异步的,directive()执行时,数据并没有回调出来,以至于在directive中取不到userInfo的值
解决方法:
app.run(['$rootScope', 'baseHttpService', function ($rootScope, baseHttpService) { //获取当前登录人用户名 baseHttpService.doGet(null, path.system.currentUser).then(data => { $rootScope.userInfo = data.data; $rootScope.$broadcast('USER_INFO', $rootScope.userInfo); }); }]);
使用广播的方式,把userinfo作为参数广播出去,在组件中进行监听,就可以获取到值。