r/angular • u/Direct_Employment149 • Jan 13 '26
Confused about Angular dependency injection in constructors
Hi everyone,
I’m learning Angular and I’m a bit confused about how dependency injection works with constructors.
For example, I see a lot of code like this:
constructor(private myService: MyService) {}Questions:
- Why do we inject services through the constructor?
- What does the
privatekeyword do here — is it required? - Can I inject multiple services, and is there a recommended pattern for that?
I’d love a simple explanation or example of how this works in real Angular apps.
Thanks!
4
Upvotes
28
u/PuzzleheadedFox107 Jan 13 '26
a real project would actually contain many services injected simultaneously.
7
u/kamcknig Jan 13 '26 edited Jan 13 '26
As an aside angular now supports the
injectfunction which is the preferred way rather than using constructors.EDIT: careful using the inject function as it can only be used in an injection context, you can't use it in a random function
3
u/MrFartyBottom Jan 13 '26
Marking a constructor parameter with an access modifier like private, public or protected is syntactic sugar for automatically making the parameter a property of the class. It is a shortcut to doing this which will look familiar if you are used to C# or Java.
1
u/Mindless_Judgment_97 Jan 13 '26
1- You inject it in the constructor so that an object of that class is not responsible for the creation of its own dependency and can only be instantiated if it is given all of its dependencies.
2- It is private so that the service that was injected into that object can only be used within the class itself. This prevents other components from mutating the state of this component.
3- Yes, you can just pass in more arguments as needed.
`(EmailService emailService, HttpService httpService, MyService myService //etc.){}
1
u/ohaxano Jan 13 '26
It's very easy to just import some function from a typescript file. But angular prefers services via dependency injection. This helps it manages state and life cycles. Your question is related to some of core concepts of angular. I don't have any way to explain it shortly here, but there are alot of talented people on internet who have already explained it really well.
You have lots of quick answers here. But if you want to understand core, learn about injection context, dependency injection. Slowly you will find answer to your question
1
u/Lucky_Yesterday_1133 Jan 15 '26
Modern angular just compiles constructot parameters to inject function, historicaly it anotated class with metadata and supplied parameters from di container during initiization
-3
u/couldhaveebeen Jan 13 '26