Gurnard
Gurnard

Reputation: 1775

Angular 6 injecting service into class without using the constructor

Using Angular 6 and Typescript 2.7. I have a class with a constructor that I pass arguments to when I create an instance from a controller. This class also has a service that needs to be injected. But then the controller that creates the instance needs to provide the service as a parameter. Is this common or is there a way to just inject the service in the class and not the constructor. I have read in other posts that the constructor should only be used to inject dependencies.

So I have the configuration class that takes simple string parameters.

export class Configuration{
    //public uiService: UiService;
    public configName:string;
    public configType: ConfigType;
    public shape:any;

    constructor(_configName: string, _configType: ConfigType){
        this.configName = _configName;
        this.configType = _configType;
....

I create a new instance of this class from my controller like this:

let config = new Configuration("NEWconfiguration", configType);

I have a common service with utility functions that I need to use in the Configuration class. Reading here and other sites I see that this should be injected through the constructor. So then my configuration constructor would include a new parameter for the service and then the controller would inject it. But the service is not used in the controller so I don't want to have to include it there.

Is there a way in the Configuration class to access the service without using the constructor? Or is this bad practice. I think I could create an instance of the service within the Configuration class or make the functions in the service static but then I am not using dependency injection. Does that matter?

Upvotes: 1

Views: 1036

Answers (1)

raymondboswel
raymondboswel

Reputation: 591

I faced a similar issue recently, where I had to create multiple instances of the same class, which isn't possible with Angular DI, which creates singletons by default. The class instances did however have dependencies on other services in my application.

The way I solved it was to inject the dependencies into my controller, and instantiate the classes using their constructors without DI.

Let me know if the above is sufficient, if not I can add example code to improve clarity.

Upvotes: 1

Related Questions