Login to manage your account

Please enter a valid email address.
Forgot Password?
Please enter a valid password.
OR

Don't have an account yet? Sign up

What is dependency injection in Angular, and how do providers and injection scopes work?

Dependency injection means a class declares what it needs in its constructor and Angular supplies it, rather than the class constructing its own dependencies. That is what makes services swappable in tests.

@Injectable({ providedIn: 'root' })
export class OrderService {
  constructor(private http: HttpClient) {}
}

The injector hierarchy is the part interviewers probe. Angular resolves a dependency by walking up from the component's injector to the root injector, and the first provider it finds wins.

  • providedIn: 'root' — one instance for the whole application, and tree-shakable, so it is dropped from the bundle if nothing injects it. This is the default you should use.
  • Providing in a component's providers array — a new instance for each instance of that component and its children. Useful when a service holds per-component state.
  • Providing in a lazy-loaded module creates a separate instance for that module, which surprises people who expected a singleton.

Note: Injection tokens are worth mentioning. Since interfaces do not exist at runtime, you use an InjectionToken to inject a configuration object or a non-class value.

All Angular interview questions

Login to manage your account

Please enter a valid email address.
Forgot Password?
Please enter a valid password.
OR

Don't have an account yet? Sign up as