简体   繁体   English

如何在纯ES5(Javascript)中为角度组件注入自定义服务?

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

I have a working angular2 Componen t. 我有一个工作angular2 Componen t。 I implemented a class for some service (using ng.core.Class if that matters). 我为一些服务实现了一个类(如果重要的话,使用ng.core.Class )。 What are the minimal steps to inject my service to my Component ? 将我的服务注入我的Component的最小步骤是什么? Should I include my service in bootstrap function? 我应该在bootstrap功能中包含我的服务吗? Should I use any of ng.core.Inject or ng.core.Injectable? 我应该使用ng.core.Injectng.core.Injectable?任何一个ng.core.Injectable? All my experiments failed so far. 到目前为止我的所有实验都失败

You can do it super simple. 你可以做到超级简单。 Just create a class an pass it through providers property or through bootstrap 只需创建一个类,通过providers属性或通过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 或者通过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) (您可以在评论中找到它的一些使用示例)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM