javascriptangularjsangularangularjs-rootscope

AngularJS $rootScope.$on alternative in context of migration to Angular2


Our AngularJS project had start it's long way to the modern Angular.

The ngMigration util recommend me to remove all the $rootScope dependecies because Angular doesn't contain a similar concept like $rootScope. It is pretty simple in some cases but I don't know what to do with event subscription mechanisms.

For example I have a some kind of Idle watchdog:

angular
    .module('myModule')
    //...
    .run(run)

//...       
function run($rootScope, $transitions, Idle) {
    $transitions.onSuccess({}, function(transition) {
        //...
        Idle.watch(); // starts watching for idleness
    });

    $rootScope.$on('IdleStart', function() {
        //...
    });

    $rootScope.$on('IdleTimeout', function() {
        logout();
    });
}

On which object instead of $rootScope I have to call the $on function if I want to get rid of the $rootScope?

UPD

The question was not about "how to migrate on Angular2 event system". It was about how to remove a $rootScope dependencies but keep a event system. Well it seems to be impossible.


Solution

  • I don't know what to do with event subscription mechanisms.

    Angular 2+ frameworks replace the $scope/$rootScope event bus with observables.

    From the Docs:

    Transmitting data between components

    Angular provides an EventEmitter class that is used when publishing values from a component. EventEmitter extends RxJS Subject, adding an emit() method so it can send arbitrary values. When you call emit(), it passes the emitted value to the next() method of any subscribed observer.

    A good example of usage can be found in the EventEmitter documentation.

    For more information, see