简体   繁体   中英

$rootScope.$emit and $on

I'm developing a big app with Angular, and I have the need to launch an event with $rootscope.$emit, and listen to this event inside a factory. I can't do that inside a controller because, when I init the User, the controller hasn't loaded yet.

The code works, but I want to know if this is the best way to do that.

Factory one, which emit the event:

angular
.module('app.core')
.factory('AuthenticationService', ['$rootScope', 'requestHttpService', AuthenticationService])

    function AuthenticationService($rootScope, requestHttpService) {
        var isLoggedIn = false;
        return {
            logIn: logIn
        }
        function logIn(action) {
            return requestHttpService.runOpenRequest(action)
                    .then(logInComplete)
                    .catch(logInError);

            function logInComplete(userData) {
                $rootScope.$emit('initUser', userData);
            }

            function logInError(error) {
                console.log('Something went wrong:  ' + error);
            }
        }
    };

And factory two, which listen to the event:

angular
   .module('app.user')
   .factory('manageUser', ['$rootScope', manageUserFactory]);

    function manageUserFactory($rootScope) {
        var user = {'id': '', 'name': ''};
        $rootScope.$on('initUser', function (event, userData) {
            initUser(userData);
        });

        return {
            initUser: initUser
        }

        function initUser(userData) {
           user = {'id': userData.id, 'name': userData.name};
        }
    };

I will suggest not to use events here.

As you are using $emit and $emit moves upward in the scope hierarchy including the current scope on which it is emitted and here in your example $rootScope is already at the top. So it will be used only to notify events binded to $rootScope .

I will suggest to call the factory method directly by injecting it as below: replace $rootScope.$emit('initUser', userData); with manageUser.initUser(); by injecting manageUser faactory in AuthenticationService .

Events are least preferred because of their performace cost.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM