Angular

Services & Dependency Injection

Services, @Injectable, providedIn, dependency injection, hierarchical injectors, injection tokens, providers

20 interview questions·
Junior
1

What is a service in Angular?

Answer

A service is a TypeScript class decorated with @Injectable that encapsulates business logic or shared data. Services follow the separation of concerns principle by extracting reusable logic out of components. They can be injected into other classes through Angular's dependency injection system, promoting code modularity and testability.

2

Which decorator makes a class injectable in Angular?

Answer

The @Injectable decorator is mandatory for a class to be used as a service in Angular's dependency injection system. This decorator allows Angular to generate the necessary metadata to resolve the service's dependencies. Without @Injectable, the TypeScript compiler would not preserve the type information needed for injection, causing runtime errors.

3

What is the correct syntax to create a basic service?

Answer

The complete syntax for creating an Angular service includes importing the Injectable decorator from @angular/core, then applying it to a class with the providedIn option. This modern configuration automatically registers the service in the application's root injector. The providedIn: 'root' option is the best practice as it enables tree-shaking and guarantees a global singleton.

4

What does providedIn: 'root' mean in @Injectable?

5

How to inject a service into a component?

+17 interview questions

Master Angular for your next interview

Access all questions, flashcards, technical tests, code review exercises and interview simulators.

Start for free