I have angular class that represents shape. I want to be able to instantiate multiple instances of that class using constructor.
The constructor takes multiple arguments representing properties of that shape.
constructor(public center: Point, public radius: number, fillColor: string, fillOpacity: number, strokeColor: string, strokeOpacity: number, zIndex: number)
Inside my class I want to use service that provides capability to draw shapes on the map. Is it possible to inject that service into my class and still use constructor the standard way.
So I want to do something like below and have Angular automatically resolve injected dependency.
constructor(public center: GeoPoint, public radius: number, fillColor: string, fillOpacity: number, strokeColor: string, strokeOpacity: number, zIndex: number, @Inject(DrawingService) drawingService: DrawingService)
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.
@Inject() is a manual mechanism for letting Angular know that a parameter must be injected. Injecting ChatWidget component to make the component behave like a singleton service so that the component state remain same across the app.
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.
The @Injectable decorator aims to actually set some metadata about which dependencies to inject into the constructor of the associated class. It's a class decorator that doesn't require parameters. Without this decorator no dependency will be injected...
I've managed to resolve my problem.
Angular 2 - 4 provides reflective injector that allows to inject dependencies outside of constructor parameters.
All I had to do was to import Reflective injector from @angular/core
.
import {ReflectiveInjector} from '@angular/core';
And then:
let injector = ReflectiveInjector.resolveAndCreate([DrawingService]); this.drawingApi = injector.get(DrawingService);
The class doesn't even have to be decorated with the @Injectable
decorator. The only problem is that I have to provide all dependencies for DrawingService and all the nested dependencies, so that is hard to maintain.
EDIT:
Angular 5
import { Injector } from "@angular/core"; const injector = Injector.create([ { provide: DrawingService } ]); this.drawingApi = injector.get(DrawingService);
Angular 6
import { Injector } from "@angular/core"; const injector = Injector.create({ providers: [ { provide: DrawingService }, ] }); this.drawingApi = injector.get(DrawingService);
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