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

不打扰是莪最后的温柔 提交于 2019-11-26 21:52:32

问题


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 inject my service to my Component? Should I include my service in bootstrap function? Should I use any of ng.core.Inject or ng.core.Injectable? All my experiments failed so far.


回答1:


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)


来源:https://stackoverflow.com/questions/34532138/how-to-inject-custom-service-to-angular-component-in-plain-es5-javascript

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!