🚀 What are Services?
- Services are classes that provide reusable functionality across your Angular application.
- They help encapsulate business logic and data access in a centralized way.
📁 1. Create a Service
Suppose you want to create a DataService to manage data operations.
Generate the service:
ng generate service data
Inside data.service.ts:
import { Injectable } from '@angular/core';
@Injectable({
providedIn: 'root'
})
export class DataService {
private data: any[] = [];
constructor() { }
getData() {
return this.data;
}
addData(item: any) {
this.data.push(item);
}
}
📄 2. Inject and Use the Service in a Component
In app.component.ts:
import { Component, OnInit } from '@angular/core';
import { DataService } from './data.service';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent implements OnInit {
data: any[] = [];
constructor(private dataService: DataService) {}
ngOnInit() {
this.data = this.dataService.getData();
}
addItem(item: any) {
this.dataService.addData(item);
}
}
In app.component.html:
<div>
<ul>
<li *ngFor="let item of data">{{ item }}</li>
</ul>
<button (click)="addItem('New Item')">Add Item</button>
</div>
📦 3. Folder Structure Overview
/src
/app
/data
data.service.ts
app.component.ts
app.component.html
app.module.ts
🎯 Quick Tips
| Tip | Description |
|---|---|
@Injectable() |
Decorator that marks a class as a service that can be injected. |
| ProvidedIn | Specifies where the service should be provided (e.g., root). |
| Dependency Injection | Angular's way of providing services to components and other services. |
⚡ Why Use Services?
- Centralize business logic and data access 📦
- Promote code reusability and maintainability 🔄
- Facilitate testing and debugging 🧪
Comments
Post a Comment