Issue
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.
Solution
Injections only works with classes that are instantiated by Angulars dependency injection (DI).
- You need to
- add
@Injectable()
toMyClass
and - provide
MyClass
likeproviders: [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).
- An alternative approach is to configure a custom injector like
With the new static injector
constructor(private injector:Injector) {
let childInjector = Injector.create({ providers: [MyClass], parent: this.injector});
let myClass : MyClass = childInjector.get(MyClass);
}
With the deprecated ReflectiveInjector
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
- Yet another way is to create the instance yourself:
constructor(ms:myService)
let myClass = new MyClass(ms);
Answered By - Günter Zöchbauer
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.