Injecting Across Frameworks
Simple Angular 1.x service:
Simple Angular 2 component that will have an Angular 1.x service injected into it:
import {A1UpgradeService} from '../services/a1-upgrade-service';
@Component({
selector: 'a2-using-a1-service',
template: `<p>{{ message }}</p>`
})
export class A2UsingA1Service {
message = '';
constructor(@Inject('a1UpgradeService') a1UpgradeService:A1UpgradeService) {
this.message = a1UpgradeService.data;
}
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:
import {Injectable} from '@angular/core';
@Injectable()
export class A2DowngradeService {
fetchData() {
return 'some data';
}
}
Lastly, Angular 1.x must be informed about the Angular 2 service:
// The service to downgrade
import {A2DowngradeService} from './services/a2-downgrade'
// Import the upgradeAdapter singleton
import {upgradeAdapter} from './upgrade-adapter';
// Name the application
const APPNAME = 'angular-upgrade-example';
// Register classic Angular 1 modules
angular
.module(APPNAME)
.factory('a2DowngradeService',
Using this downgraded service in an Angular 1.x directive is as simple as: