Angular Service
Angular Service
Contents
• What is Angular Service?
• Creating Angular Service
• Anatomy of Angular Service
• Providing Service
• Using Service
• Example
What is Angular Service?
• An Angular service is a TypeScript class that plays a critical role in Angular applications.
• Services are used to provide a centralized place for managing and sharing data, logic, and
functionality across different parts of an Angular application, such as components, directives,
and other services.
• They help promote modularity, reusability, and maintainability in your Angular application.
Creating an Angular Service
To create an Angular service, you typically use the Angular CLI, which makes it easier to
generate service files. Run the following command to generate a service:
This will create a file called my-service.service.ts and an associated test file.
Anatomy of an Angular Service
• An Angular service is a TypeScript class with the @Injectable decorator.
• This decorator is required to ensure that the service can be injected into other Angular
components.
@Injectable({
providedIn: 'root' // Specifies where the service should be available
})
export class MyService {
// Service logic and data
}
Providing an Angular Service
The providedIn property in the @Injectable decorator specifies where the service should be
available.
@Component({
selector: 'app-my-component',
template: `
<p>{{ serviceData }}</p>
`
})
export class MyComponent {
serviceData: any;
@Injectable({
providedIn: 'root'
})
export class MyService {
private data: string[] = [];