Dependency Injection — Angular Technical Interview Questions & Answers
Dependency Injection
Dependency Injection
- DI means Angular creates the object and passes it in the constructor. constructor(private marks: MarksService). You don’t call new. Providers tell Angular how to make it.
- providedIn: 'root' → one singleton. providedIn a component → new instance for that component tree. Use root for MarksService. Use component provider only when you want isolation.
- Trap: circular inject (A needs B needs A). Split a third helper. Another trap: forgetting to provide a non-root service and getting NullInjectorError.
Technical Interview Tip: constructor inject + providedIn. NullInjectorError meaning.
Code Examples for Dependency Injection
Dependency Injection — working example
import { Injectable } from "@angular/core";
@Injectable({ providedIn: "root" })
export class UserService {
getName() {
return "Asha";
}
}Dependency Injection — services hold shared logic; Angular DI injects them into components.
How to Explain Dependency Injection to an Interviewer
What is dependency injection in Angular?
Framework creates deps constructor(private svc: …)
What is NullInjectorError?
Service not provided