What is a service in Angular?
Answer
A service is a TypeScript class decorated with @Injectable() that encapsulates reusable, non-UI logic and can be shared across multiple components. Services follow the single responsibility principle — handle specific functionality: data fetching, business logic, state management, logging, authentication. Why use services? Without services, components would contain all logic and data — components would be large, untestable, and logic would be duplicated. Services allow logic to be defined once and injected into any component that needs it. Creating a service: ng generate service user creates: @Injectable({ providedIn: "root" }) export class UserService { private users = []; getUsers() { return this.http.get("/api/users"); } }. providedIn: "root" registers the service as a singleton at the application root level — one instance shared across the entire application. Injecting a service: Angular's DI system automatically provides the service via constructor injection: constructor(private userService: UserService) {}. The class name as type annotation is the injection token. Service scope: providedIn: "root" (app-wide singleton), provided in a specific module (scoped singleton), or provided directly in a component's providers array (new instance per component). HttpClient, Router, ActivatedRoute are all examples of Angular built-in services.