Services in Angular allow you to keep logic and data separate from the user interface. This way, multiple components can use the same service to share data or functions, making the code cleaner and easier to maintain.
Angular services are typically singletons within an injector scope. This means components that inject the same service share one instance, so changes in one component affect the others.
import { Component } from '@angular/core'; import { DataService } from './data.service'; @Component({ selector: 'app-example', template: '<p>Example works!</p>', standalone: true }) export class ExampleComponent { constructor( /* What goes here? */ ) {} }
Angular injects services by declaring them as constructor parameters with an access modifier like private or public. This tells Angular to provide the service instance automatically.
If a service is provided in a component's providers array, Angular creates a new instance for that component only. To share data, the service should be provided at a higher level like root.
Services provided in root are singletons that live as long as the app runs. Destroying a component does not destroy the service, so its data stays available.