加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 综合聚焦 > 服务器 > 安全 > 正文

angularjs – Angular .controller()在.run()之前运行

发布时间:2020-12-17 17:44:59 所属栏目:安全 来源:网络整理
导读:我在.run()中有一个ajax调用,它将一个变量加载到$rootScope中 在与视图关联的控制器中需要该变量. 有时在.controller加载时刷新(F5)时,$rootScope.user.fedUnit内部没有任何内容导致: TypeError:无法读取未定义的属性’fedUnit’ 有没有什么方法可以延迟加
我在.run()中有一个ajax调用,它将一个变量加载到$rootScope中
在与视图关联的控制器中需要该变量.

有时在.controller加载时刷新(F5)时,$rootScope.user.fedUnit内部没有任何内容导致:

TypeError:无法读取未定义的属性’fedUnit’

有没有什么方法可以延迟加载控制器直到完成.run()之后?
似乎无法找到它.

app.run(function($rootScope,$http,$location,SessionFactory,TokenHandler) {
    token = TokenHandler.getToken();
    if ( token != null ) {
        SessionFactory.get( { token : token },function success(response,responseHeaders) {
                $rootScope.user = response;
            }
        );
    }
});

app.controller('UnitController',function($scope,$rootScope,UnitFactory) {
    $scope.updateUnits = function () {
        UnitFactory.query({fedUnit: $rootScope.user.fedUnit},responseHeaders) { ...

$rootScope.foo = $q.defer();
$rootScope.foo.resolve(); when AJAX is done;
$rootScope.foo.promise.then(..) in the controller.

感谢@misterhiller(twitter)

解决方法

功能代码块的解决方案:

app.run(function($rootScope,$q,TokenHandler) {

    $rootScope.ajaxCall = $q.defer();

    token = TokenHandler.getToken();
    if ( token != null ) {
        SessionFactory.get( { token : token },responseHeaders) {
                $rootScope.user = response;

                $rootScope.ajaxCall.resolve();
            }
        );
    }
});

app.controller('UnitController',UnitFactory) {

    $scope.ajaxCall.promise.then(function() {
        $scope.updateUnits = function () {
            UnitFactory.query({fedUnit: $scope.user.fedUnit});
        }
    });
});

我不在控制器中使用$rootScope.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读