最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

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

programmeradmin2浏览0评论

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.

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.

Share Improve this question edited Feb 25, 2016 at 1:37 twernt 20.6k5 gold badges34 silver badges41 bronze badges asked Dec 30, 2015 at 15:15 Sergey P. aka azureSergey P. aka azure 4,7721 gold badge34 silver badges25 bronze badges 1
  • I refer to current beta version of angular2 in this question. – Sergey P. aka azure Commented Dec 30, 2015 at 15:16
Add a ment  | 

1 Answer 1

Reset to default 12

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 ponent

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 ments)
发布评论

评论列表(0)

  1. 暂无评论