Services are reusable pieces of code that can be shared across your Angular application. They typically handle data fetching, business logic, or other functionality that multiple components need to access.
You can create a service with the Angular CLI with the following command:
ng generate service CUSTOM_NAME
This creates a dedicated CUSTOM_NAME.ts file in your src directory.
You can also manually create a service by adding the @Injectable() decorator to a TypeScript class. This tells Angular that the service can be injected as a dependency.
Here is an example of a service that allows users to add and request data:
// 📄 src/app/basic-data-store.ts
import {Injectable} from '@angular/core';
@Injectable({providedIn: 'root'})
export class BasicDataStore {
private data: string[] = [];
addData(item: string): void {
this.data.push(item);
}
getData(): string[] {
return [...this.data];
}
} When you use @Injectable({ providedIn: 'root' }) in your service, Angular:
This is the recommended approach for most services.
Once you've created a service with providedIn: 'root', you can inject it anywhere in your application using the inject() function from @angular/core.
import {Component, inject} from '@angular/core';
import {BasicDataStore} from './basic-data-store';
@Component({
selector: 'app-example',
template: `
<div>
<p>{{ dataStore.getData() }}</p>
<button (click)="dataStore.addData('More data')">Add more data</button>
</div>
`,
})
export class Example {
dataStore = inject(BasicDataStore);
} import {inject, Injectable} from '@angular/core';
import {AdvancedDataStore} from './advanced-data-store';
@Injectable({
providedIn: 'root',
})
export class BasicDataStore {
private advancedDataStore = inject(AdvancedDataStore);
private data: string[] = [];
addData(item: string): void {
this.data.push(item);
}
getData(): string[] {
return [...this.data, ...this.advancedDataStore.getData()];
}
} While providedIn: 'root' covers most use cases, Angular offers additional ways to provide services for specialized scenarios:
You can learn more about these advanced patterns in the next guide: defining dependency providers.
Super-powered by Google ©2010–2025.
Code licensed under an MIT-style License. Documentation licensed under CC BY 4.0.
https://angular.dev/guide/di/creating-and-using-services