When dealing with injections, it is important to note that they only work with classes that are instantiated by Angular's dependency injection (DI).
- To properly utilize injections, make sure to:
- Include
@Injectable()
in the definition of MyClass
and
- Specify
MyClass
in the providers array like providers: [MyClass]
within a component or NgModule.
By following these steps, when you inject MyClass
, an instance of MyService
will be passed to it during instantiation via DI.
- Another approach is to set up a custom injector as follows:
Using the updated static injector:
constructor(private injector:Injector) {
let childInjector = Injector.create({ providers: [MyClass], parent: this.injector});
let myClass : MyClass = childInjector.get(MyClass);
}
Utilizing 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 method ensures that myClass
will be an instance of MyClass
created by Angular's DI, with myService
injected into it upon instantiation.
For more information, refer to Getting dependency from Injector manually inside a directive
- Alternatively, you can manually create the instance yourself:
constructor(ms:myService)
let myClass = new MyClass(ms);