Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to inject upgraded Angular 1 service/factory to Angular 2 component in ES5?

I have an Angular1 service with name, say, 'myService'

I then upgraded it using the Angular2 UpgradeAdapter like this:

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

Now I need to inject it to the angular2 component. Official upgrade guide only has typescript version for now. In typescript you use @Inject anotation with the service name for it like so:

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

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

like image 272
Dmitry Klochkov Avatar asked Jan 20 '16 12:01

Dmitry Klochkov


1 Answers

To complete the pixelbits' answer, you need also define my service within the providers list either:

  • At the application level

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

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

It depends on what you want to do: share your service instance for all elements in the Angular2 application or per component.

This answers could give more details on dependency injection in Angular2 with ES5: Dependency Injection in Angular 2 with ES5.

Edit

In fact, there is a subtlety. IN the case of upgrade you need not to bootstrap using the ng.platform.browser.bootstrap function but the one from the upgrade object.

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

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

In fact, when you call the upgradeNg1Provider method on the upgrade, corresponding providers are registered within its associated injector. This means that you don't need to specify them at described above.

So you simply need to do that where you want to inject:

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

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

Hope it helps you, Thierry

like image 152
Thierry Templier Avatar answered Sep 27 '22 00:09

Thierry Templier