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

}


4 comments:

  1. With your tips, my programming has become much more correct! Thanks for the blog

    ReplyDelete
  2. The use of the services of this type involves the selecting of appropriate provider. We can also install such programs by default.

    ReplyDelete
  3. Your explanations about Inject AngularJS services into Angular 2 is useful for my angularjs 2 training class. Thanks to shared your knowledge with me.

    ReplyDelete
  4. nice blog
    great information
    Cosmetology Course
    Advance Diploma in Cosmetology,Grand Master in Cosmetology,
    Professional Diploma in Cosmetology,International Diploma in Cosmetology.

    ReplyDelete