Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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? 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.

like image 403
Sergey P. aka azure Avatar asked Dec 30 '15 15:12

Sergey P. aka azure


People also ask

How do you inject a service into a component in Angular?

The @Injectable() decorator defines a class as a service in Angular and allows Angular to inject it into a component as a dependency. Likewise, the @Injectable() decorator indicates that a component, class, pipe, or NgModule has a dependency on a service. The injector is the main mechanism.

Can you inject a service into a service Angular?

You can inject an Angular service in a component, service, directive etc by specifying the service and its type in a component's constructor. Note that injecting a service through a class constructor is, in general, tree-shakable.

What is injectable () in Angular service?

Marking a class with @Injectable ensures that the compiler will generate the necessary metadata to create the class's dependencies when the class is injected. The following example shows how a service class is properly marked so that a supporting service can be injected upon creation.

How many ways we can inject service in Angular?

There are three types of Dependency Injections in Angular, they are as follows: Constructor injection: Here, it provides the dependencies through a class constructor. Setter injection: The client uses a setter method into which the injector injects the dependency.


1 Answers

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)
like image 121
Eric Martinez Avatar answered Oct 13 '22 02:10

Eric Martinez