1

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?

1 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

2 Comments

so your constructor was like this constructor(myCommonService:CommonService, configName:string){... and you called it like this new MyClass(instanceOfMyService, "newConfig"){... where in the controller you had injected CommonService.
Exactly. I understand the worry about injecting something in your controller that is only used inside another class, but at some point you have to hook into the DI system.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.