How to inject custom service to angular component in plain ES5 (Javascript)?

前端 未结 1 532
北荒
北荒 2020-12-06 20:17

I have a working angular2 Component. I implemented a class for some service (using ng.core.Class if that matters). What are the minimal steps to in

相关标签:
1条回答
  • 2020-12-06 21:20

    You can do it super simple. Just create a class an pass it through providers property or through bootstrap

    For example

     // Alternative 1
     var Service = ng.core.Class({
      constructor : function() {},
      someFunction : function() {
        console.log('Some function');
      }
    })
    
    // Alternative 2
    var Service = function() {}
    Service.prototype.someFunction = function() {
      console.log('Some function');
    }
    

    Then pass it to the component

    var Component = ng.core.
          Component({
            selector: 'cmp',
            template : '',
            providers : [Service]
          }).
          Class({
            constructor: [Service, function(svc) {
              svc.someFunction();
            }]
          });
    

    Or through bootstrap

    ng.platform.browser.bootstrap(Component, [Service]);
    

    Here's an example so you can take a look at it.

    Reference

    • Class (you can find some examples of its usage in the comments)
    0 讨论(0)
提交回复
热议问题