Injecting Across Frameworks

    Simple Angular 1.x service:

    Simple Angular 2 component that will have an Angular 1.x service injected into it:

    1. import {A1UpgradeService} from '../services/a1-upgrade-service';
    2. @Component({
    3. selector: 'a2-using-a1-service',
    4. template: `<p>{{ message }}</p>`
    5. })
    6. export class A2UsingA1Service {
    7. message = '';
    8. constructor(@Inject('a1UpgradeService') a1UpgradeService:A1UpgradeService) {
    9. this.message = a1UpgradeService.data;
    10. }

    Angular 2.x services can be downgraded and injected into Angular 1. In normaloperation, Angular 2.x services would be bootstrapped with the application, butbecause of ng-upgrade being a hybrid mode, this is not the case. The upgradeadapter comes with an method that must be used in the interim.

    Here is a very simple Angular 2 service:

    1. import {Injectable} from '@angular/core';
    2. @Injectable()
    3. export class A2DowngradeService {
    4. fetchData() {
    5. return 'some data';
    6. }
    7. }

    Lastly, Angular 1.x must be informed about the Angular 2 service:

    1. // The service to downgrade
    2. import {A2DowngradeService} from './services/a2-downgrade'
    3. // Import the upgradeAdapter singleton
    4. import {upgradeAdapter} from './upgrade-adapter';
    5. // Name the application
    6. const APPNAME = 'angular-upgrade-example';
    7. // Register classic Angular 1 modules
    8. angular
    9. .module(APPNAME)
    10. .factory('a2DowngradeService',

    Using this downgraded service in an Angular 1.x directive is as simple as: