angularjs - $rootScope.$on 事件未触发

标签 angularjs

我试图在用户登录后触发一个功能。我尝试将广播包装在计时器中,因为我看到有些人建议这样做,但它似乎不起作用。有些人遇到的问题是他们的 Controller 尚未初始化,但我在 app.run 中有 $on,所以它应该已经发生了。

app.run(['$rootScope', '$http', '$cookies', '$cookieStore', function ($rootScope, $http, $cookies, $cookieStore) {

$rootScope.logout = function () {

    $http.post('API' + '/api/Account/Logout')
        .success(function (data, status, headers, config) {
            $http.defaults.headers.common.Authorization = null;
            $http.defaults.headers.common.RefreshToken = null;
            $cookieStore.remove('_Token');
            $cookieStore.remove('_RefreshToken');
            $rootScope.username = '';
            $rootScope.loggedIn = false;
            window.location = '#/signin';
        });

}

$rootScope.$on('loggedIn', function (event) {
    if ($http.defaults.headers.common.RefreshToken != null) {
        var params = "grant_type=refresh_token&refresh_token=" + $http.defaults.headers.common.RefreshToken;
        $http({
            url: 'http://localhost:52644/Token',
            method: "POST",
            headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
            data: params
        })
        .success(function (data, status, headers, config) {
            $http.defaults.headers.common.Authorization = "Bearer " + data.access_token;
            $http.defaults.headers.common.RefreshToken = data.refresh_token;

            $cookieStore.put('_Token', data.access_token);
            $cookieStore.put('_RefreshToken', data.refresh_token);

            $http.get('http://localhost:52644/api/Account/GetUserInfo')
                .success(function (data, status, headers, config) {
                    if (data != "null") {
                        $rootScope.userEmail = data.replace(/["']{1}/gi, "");//Remove any quotes from the username before pushing it out.
                        $rootScope.userFirstName = data.FirstName;
                        $rootScope.loggedIn = true;
                    }
                    else
                        $rootScope.loggedIn = false;
                });


        })
        .error(function (data, status, headers, config) {
            $rootScope.loggedIn = false;
        });
    }
});

}]);

app.controller('signInCtrl', ['$scope', '$rootScope', '$http', '$cookies', '$cookieStore', '$location', '$routeParams', '$uibModalInstance', '$timeout' ,function ($scope, $rootScope, $http, $cookies, $cookieStore, $location, $routeParams, $uibModalInstance, $timeout) {
$scope.message = $routeParams.message;
$scope.signIn = function () {
    $scope.showMessage = false;
    var params = "grant_type=password&username=" + $scope.username + "&password=" + $scope.password;
    $http({
        url: 'http://localhost:52644/token',
        method: "POST",
        headers: {
            'Content-Type': 'application/x-www-form-urlencoded'
        },
        data: params
    })
    //$http.post('http://localhost:52644/token', params, {
    //    headers: {
    //        'Content-Type': 'application/x-www-form-urlencoded'

    //    }
    .success(function (data, status,
        s, config) {
        $http.defaults.headers.common.Authorization = "Bearer " + data.access_token;
        $http.defaults.headers.common.RefreshToken = data.refresh_token;

        $cookieStore.put('_Token', data.access_token);
        $rootScope.$broadcast('loggedIn');
        $timeout(function () {
            $rootScope.$broadcast('loggedIn');
        }, 100);
        $uibModalInstance.close();
    })
    .error(function (data, status, headers, config) {
        $scope.message = data.error_description.replace(/["']{1}/gi, "");
        $scope.showMessage = true;
    });
}

}]);

最佳答案

您不能广播到 $rootScope 事件处理程序(或与其一起广播)。您最多只能发出 $emit。

$rootScope.$emit('loggedIn');

根据 documentation

$emit(name, args); Dispatches an event name upwards through the scope hierarchy notifying the registered $rootScope.Scope listeners.

The event life cycle starts at the scope on which $emit was called. All listeners listening for name event on this scope get notified. Afterwards, the event traverses upwards toward the root scope and calls all registered listeners along the way. The event will stop propagating if one of the listeners cancels it.

关于angularjs - $rootScope.$on 事件未触发,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36380300/

相关文章:

javascript - 当添加到 Angular 之外的 dom 时,如何获取要渲染的 Angular 指令?

angularjs - 如何从左向右滑动 Ionic 列表项?

javascript - 如何在ngRepeat中仅重复 "key"一次(AngularJS)

javascript - 如何自定义 Angular ui-grid 行背景颜色?

javascript - 将计算值传递给 ng-model

angularjs - 指令模型绑定(bind)在 angular ui bootstrap tabs 指令下不起作用

javascript - 如何将 csv 转换为数组

javascript - Angularjs - 与标准 html 元素同名的自定义指令

javascript - 我可以在angular js asp.net mvc中调用Controller中的Route Provider服务吗

ajax - 如何使用 angularjs $http 修复我的 jsonp 回调以解决 "unexpected token"错误?