Thursday, March 30, 2017

Inject AngularJS services into Angular 2


When you are running AngularJS and Angular side by side, then you may need to inject AngularJS default services such as $rootScope, $timeout, $state (UI-Router) etc.

In order to use the AngularJS default services, you need to define a provider. The upgrade module already defined a provider for $rootScope, hence you can use it directly as outlined in my other blog.

Let’s see how to inject the UI-Router $state into Angular. Upgrade Module internally stores the Angular JS injector. In our Angular 2 module, we can define a provider which utilizes the Angular JS injector to return the reference.

So first define a provider in Angular 2 as shown below

@NgModule({
    imports: [ ... ],
    declarations: [ ... ],
    providers: [
        { provide: '$state', useFactory: (i) => i.get('$state'), deps: ['$injector'] }
    ]
})

After defining the provider in the module, you can now inject the dependencies in your angular 2 components and services as shown below:

constructor(@Inject("$rootScope") private $rootScope: ng.IRootScopeService, @Inject("$state") private $state: ng.ui.IStateService) {
        // UI-Router change events

}


Inject $rootScope into Angular 2


If you have AngularJS and Angular running side by side in the same application by using Upgrade module, then you may need access $rootScope in Angular 2 part of the application.

The upgrade module already defined a provider for $rootScope, hence you directly inject $rootScope as below

@Inject("$rootScope") private $rootScope: ng.IRootScopeService

Here is the constructor DI code:

constructor(@Inject("$rootScope") private $rootScope: ng.IRootScopeService, @Inject("$state") private $state: ng.ui.IStateService) {
        // UI-Router change events

}

To inject $state and other AngularJS services please refer to my other blog