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.
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.
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.
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.
Injections only works with classes that are instantiated by Angulars dependency injection (DI).
@Injectable()
to MyClass
andMyClass
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).
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
constructor(ms:myService) let myClass = new MyClass(ms);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With