Services & Dependency Injection
Services, @Injectable, providedIn, dependency injection, hierarchical injectors, injection tokens, providers
1What is a service in Angular?
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.
2Which decorator makes a class injectable in Angular?
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.
3What is the correct syntax to create a basic service?
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.
What does providedIn: 'root' mean in @Injectable?
How to inject a service into a component?
+17 interview questions
Other Angular interview topics
TypeScript Basics
TypeScript Advanced
Angular Fundamentals
Components & Lifecycle
Angular Modules Organization
Angular CLI
Directives & Pipes
Routing & Navigation
Reactive Forms
Template-driven Forms
RxJS Fundamentals
RxJS Operators
HttpClient & API Calls
Basic State Management
Change Detection
Angular Signals
Standalone Components
Angular Unit Testing
End-to-End Testing
Build & Optimization
NgRx Fundamentals
NgRx Advanced
Angular Architecture
Performance Optimization
Security & Best Practices
Advanced RxJS Patterns
Angular Universal & SSR
Angular Micro-frontends
Master Angular for your next interview
Access all questions, flashcards, technical tests, code review exercises and interview simulators.
Start for free