How to add updated Angular 1 service / factory to Angular 2 component in ES5?

I have an Angular1 service named, say, 'myService'

Then I updated it using Angular2 UpgradeAdapter as follows:

var upgradeAdapter = new ng.upgrade.UpgradeAdapter(); upgradeAdapter.upgradeNg1Provider('myService'); 

Now I need to inject it into the Angular2 component. The official update guide has a typescript version for now. In typescript, you use @Inject anotation with the service name for it as follows:

 export class MyComponent { constructor(@Inject('myService') service:MyService) { ... } } 

What is the syntax for entering a service by name using ES5?

+4
angularjs angular
source share
2 answers

In order to answer the pixel bits, you also need to define my service in the list of providers:

  • Application level

     document.addEventListener('DOMContentLoaded', function() { ng.platform.browser.bootstrap(Cmp, [MyService]); }); 
  • At component level

     var Cmp = ng.core. Component({ selector: 'cmp', providers: [ MyService ] }). (...) Class({ constructor: [MyService, function(service) { }] }); 

It depends on what you want to do: exchange a service instance for all elements of an Angular2 application or for each component.

In this answer, you can learn more about dependency injection in Angular2 with ES5: Dependency injection in Angular 2 with ES5 .

Edit

There is actually subtlety. In the case of an update, you do not need to load using the ng.platform.browser.bootstrap function, except for the upgrade object.

 upgrade.bootstrap(document.body, ['heroApp']); 

Where heroApp is an Angular1 module containing the services and factories that I want to use in an Angular2 application.

In fact, when you call the upgradeNg1Provider method when upgrading, the corresponding providers are registered in the corresponding injector. This means that you do not need to specify them as described above.

So you just need to do what you want to enter:

 (...) Class({ constructor: [ ng.core.Inject('customService'), ng.core.Inject('customFactory'), function(cService, cFactory) { }] }); 

Miško Hevery provides an excellent plunkr for this: http://plnkr.co/edit/yMjghOFhFWuY8G1fVIEg?p=preview .

Hope this helps you, Thierry

+4
source share

Use array notation for the DI services constructor:

 .Class({ constructor: [MyService, function (service) { ... }], 
+2
source share

All Articles