22. Introduction to Services
Services are classes intended to perform specific tasks, typically logic not directly related to the view, such as data fetching, logging, validation, or shared state management.
The @Injectable() Decorator
Any class that Angular's Dependency Injector can manage must be decorated with @Injectable().
Use the CLI to generate a service:
bash ng generate service data/user // Creates src/app/data/user.service.ts
Service Example: Logger
typescript import { Injectable } from '@angular/core';
@Injectable({ // ProvidedIn metadata (since Angular 6+) providedIn: 'root' }) export class LoggerService { private logs: string[] = [];
log(message: string) {
const timestamp = new Date().toISOString();
const fullMessage = [${timestamp}] ${message};
console.log(fullMessage);
this.logs.push(fullMessage);
}
getLogs(): string[] { return this.logs; } }
The providedIn: 'root' Property
By default, generated services use providedIn: 'root'. This configures the service to be a singleton (only one instance exists) across the entire application. This is the modern, preferred way to provide application-wide services, eliminating the need to explicitly list them in the providers array of AppModule.