What is a Service?
A service is a class with a narrow, well-defined purpose. While components are responsible for the 'View', services are responsible for the 'Logic'. Common use cases include fetching data from a server, validating user input, or logging messages to a console. As an Engineering Manager, you should enforce using services to prevent 'Fat Components' and to make your business logic reusable across your entire application.
- Creating a Service
You use the Angular CLI to generate a service. It creates a TypeScript class decorated with @Injectable. The providedIn: 'root' metadata is the modern standard, making the service a singleton available everywhere.
- Injecting and Using a Service
To use a service, you 'inject' it into a component's constructor. Angular's Dependency Injection (DI) system handles the instantiation, ensuring the component receives the correct instance of the service.
The Component-Service Relationship
Services act as the data providers, while components act as the data consumers. This decoupling allows you to test your logic independently of the UI.
- Singletons vs. Multiple Instances
By default, services provided in 'root' are singletons—one instance exists for the entire app. However, if you provide a service inside a specific component's providers array, Angular creates a new, private instance just for that component and its children.
| Scope | Declaration | Behavior |
|---|---|---|
| Application | providedIn: 'root' | One instance shared by all (Singleton) |
| Module | @NgModule({ providers: [...] }) | One instance shared by all in that module |
| Component | @Component({ providers: [...] }) | New instance for every component created |