Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to inject service into class (not component)

I'd like to inject a service into a class that is not a component.

For example:

Myservice

import {Injectable} from '@angular/core'; @Injectable() export class myService {   dosomething() {     // implementation   } } 

MyClass

import { myService } from './myService' export class MyClass {   constructor(private myservice:myService) {    }   test() {      this.myservice.dosomething();   } } 

I tried and it doesn't work. It seems like service need to be used in only component or service.

Is there a way to use a service in a normal class? or it's a bad practice to use a service in a normal class.

Thank you.

like image 945
Elec Avatar asked Jan 02 '17 19:01

Elec


People also ask

How a service can be injected to a component class?

Angular provides the ability for you to inject a service into a component to give that component access to the service. The @Injectable() decorator defines a class as a service in Angular and allows Angular to inject it into a component as a dependency.

What are the different ways to inject the Angular service?

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.

Can we inject Service inside service in 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.


1 Answers

Injections only works with classes that are instantiated by Angulars dependency injection (DI).

  1. You need to
    • add @Injectable() to MyClass and
    • provide MyClass like providers: [MyClass] in a component or NgModule.

When you then inject MyClass somewhere, a MyService instance gets passed to MyClass when it is instantiated by DI (before it is injected the first time).

  1. An alternative approach is to configure a custom injector like
constructor(private injector:Injector) {    let resolvedProviders = ReflectiveInjector.resolve([MyClass]);   let childInjector = ReflectiveInjector.fromResolvedProviders(resolvedProviders, this.injector);    let myClass : MyClass = childInjector.get(MyClass); } 

This way myClass will be a MyClass instance, instantiated by Angulars DI, and myService will be injected to MyClass when instantiated.
See also Getting dependency from Injector manually inside a directive

  1. Yet another way is to create the instance yourself:
constructor(ms:myService) let myClass = new MyClass(ms); 
like image 85
Günter Zöchbauer Avatar answered Sep 28 '22 23:09

Günter Zöchbauer