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

后端 未结 2 1154
情话喂你
情话喂你 2020-12-19 12:26

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

I then upgraded it using the Angular2 UpgradeAdapter like this:

var upgradeAdapter = new ng.         


        
相关标签:
2条回答
  • 2020-12-19 12:34

    Use the array notation for constructor DI of services:

    .Class({
        constructor: [MyService, function (service) {
          ...
     }],
    
    0 讨论(0)
  • 2020-12-19 12:54

    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

    0 讨论(0)
提交回复
热议问题