I am currently working on a large Angular app and I have encountered the need to trigger an event using $rootscope.$emit, and then listen to this event inside a factory. Doing this inside a controller is not feasible because the controller hasn't loaded yet when initializing the User.
Although the code works fine, I am curious if there is a better way to achieve this.
The first factory that emits 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 the second factory that listens 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};
}
};