Dependency Injection in Angular
Dependency Injection in Angular
What is
Dependency
Injection in Angular ?
Dependancy
Injection
Chandrakanth Avula
@chandrakanth1
Scenario with Example
Let’s imagine a School with classroom:
Every day, the teacher needs things like
chalk, markers, and books to teach the
students. Now, what if the teacher had
to bring all these things from home? It
would be tiring and take a lot of time!
Chandrakanth Avula 1
Why Do We Need
Dependency Injection?
Imagine if every Teacher in the school:
Had to bring their own chalk, books, and
whiteboards.
It would waste time and resources!
Chandrakanth Avula 2
What is Dependency
Injection?
In Angular, Dependency Injection works
like the school principal:
The principal provides the resources
(services) to the teachers (components).
Teachers don’t worry about where resources
come from — they just use them!
Chandrakanth Avula 4
Injecting Dependencies
into Components
Imagine a teacher entering a classroom. They don’t bring
chalk from home. Instead, the principal (Angular)
provides the chalk they need to teach.
In Angular, services work the same way: Angular gives
components the tools they need.
Here’s how it looks in code:
Chandrakanth Avula 5
Singleton Services – One
Set of Chalk for All
Imagine a school where all teachers share the same
box of chalk. Instead of giving each teacher their own
box, the school provides one shared box. Teachers take
what they need and pass it along.
Chandrakanth Avula 6
Customizing Providers –
Private Chalkboards for Each
Classroom
Imagine a school where every classroom has its own
private chalkboard.
The chalkboard in one classroom doesn’t affect the
others. For example, the math class can write formulas
without worrying about what's on the science class
chalkboard.
Angular lets you decide:
1. Share resources globally (like chalk for the whole
school).
Keep resources private to one classroom (a specific
component).
Here’s how you create a private chalkboard ::
Chandrakanth Avula 7
Benefits of Dependency Injection
Why Angular’s School System is
Genius
Angular’s Dependency Injection (DI) is like a brilliant
school system that makes everything work smoothly:
1. Saves Time: Teachers (components) don’t need to
bring their own chalk (services). The principal
(Angular) provides it!
2. Shares Resources: One chalk box (service) can be
shared by many classrooms (components).
3. Improves Testing: Want to test the chalk without a
real classroom? Easy! Use a pretend chalk box for
testing.
Chandrakanth Avula 7
Angular Tips
Follow me to
get more
Information
and tips like
this.
Chandrakanth Avula
@chandrakanth1