Loading

Quipoin Menu

Learn • Practice • Grow

angular / Introduction to Services
interview

Q1. What are services in Angular?
Services are classes that provide specific functionality not directly related to views. They are used for tasks like fetching data from servers, validation, logging, or sharing state between components. Services are singleton by default when provided at the root level, making them ideal for sharing data and logic.

Q2. Why use services in Angular?
Services promote separation of concerns by keeping business logic out of components. They make code more maintainable, testable, and reusable. Components delegate tasks like API calls to services, staying focused on presentation. Services also enable sharing data across components without tightly coupling them.

Q3. How do you create a service in Angular?
Use the CLI:
ng generate service data
This creates a service class with @Injectable decorator. Example:
@Injectable({ providedIn: ''root'' }) export class DataService { ... }

Q4. What is the @Injectable decorator?
@Injectable marks a class as available for dependency injection. It also carries metadata about how to inject the service. The providedIn option determines the scope: ''root'' makes it a singleton across the app, or you can provide it at component/module level.

Q5. What is the difference between providedIn: ''root'' and providing in module?
providedIn: ''root'' creates a single, shared instance throughout the application and enables tree-shaking (if the service is unused, it won''t be included in the bundle). Providing in a module (using providers array) creates a service instance for that module only. Root-level is preferred for shared services.