Skip to content Skip to sidebar Skip to footer

How To Inject Custom Service To Angular Component In Plain Es5 (javascript)?

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?

Solution 1:

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

For example

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

// Alternative 2varService = function() {}
Service.prototype.someFunction = function() {
  console.log('Some function');
}

Then pass it to the component

varComponent = 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)

Post a Comment for "How To Inject Custom Service To Angular Component In Plain Es5 (javascript)?"