0% found this document useful (0 votes)
7 views

Angular Service

Uploaded by

HARSH VAIDYA
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
7 views

Angular Service

Uploaded by

HARSH VAIDYA
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 10

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:

ng generate service my-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.

import { Injectable } from '@angular/core';

@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.

Common values include:

• 'root': Makes the service a singleton, available application-wide.


• A specific module: Restricts the service's scope to a particular module.
• A component: Limits the service's availability to a specific component and its children.
Using an Angular Service
• To use an Angular service in a component, you need to inject it.
• Angular's dependency injection system handles this for you.
Using an Angular Service
import { Component } from '@angular/core';
import { MyService } from './my-service.service';

@Component({
selector: 'app-my-component',
template: `
<p>{{ serviceData }}</p>
`
})
export class MyComponent {
serviceData: any;

constructor(private myService: MyService) {


this.serviceData = myService.getData();
}
}
Implement Service Logic
Inside your service class, you can define methods and properties that encapsulate the
functionality you want to share.

@Injectable({
providedIn: 'root'
})
export class MyService {
private data: string[] = [];

addData(item: string): void {


this.data.push(item);
}
getData(): string[] {
return this.data;
}
}
?

You might also like