Setting Up a Signal-based Data Service
Create a New Angular Service: You can generate a service using Angular CLI:
bashng generate service data
Implement Signals in the Service: Modify the generated service to use Signals for managing data.
typescript// data.service.ts import { Injectable, signal } from '@angular/core'; import { Signal } from '@angular/core'; interface Item { id: number; name: string; } @Injectable({ providedIn: 'root' }) export class DataService { private itemsSignal: Signal<Item[]> = signal([]); getItems(): Signal<Item[]> { return this.itemsSignal; } addItem(newItem: Item): void { this.itemsSignal.update(currentItems => [...currentItems, newItem]); } removeItem(itemId: number): void { this.itemsSignal.update(currentItems => currentItems.filter(item => item.id !== itemId)); } }
Using the Data Service in a Component
Inject the Data Service: Use the service in your component to manage and display items.
typescript// app.component.ts import { Component } from '@angular/core'; import { DataService } from './data.service'; @Component({ selector: 'app-root', template: ` <h1>Item List</h1> <ul> <li *ngFor="let item of items()"> {{ item.name }} <button (click)="removeItem(item.id)">Remove</button> </li> </ul> <button (click)="addItem()">Add Item</button> `, }) export class AppComponent { constructor(private dataService: DataService) {} items = this.dataService.getItems(); addItem() { const newItem = { id: Date.now(), name: `Item ${Math.floor(Math.random() * 100)}` }; this.dataService.addItem(newItem); } removeItem(itemId: number) { this.dataService.removeItem(itemId); } }
Summary
In this example:
- A DataService is created that manages an array of items using Signals.
- The AppComponent subscribes to the
itemsSignal
and provides UI functionalities to add and remove items.
Benefits of Using Signals
- Reactivity: Components automatically update when the state changes, improving performance.
- Simplicity: The API is straightforward, making state management more manageable.
This approach is particularly useful in complex applications where state needs to be shared across multiple components.
No comments:
Post a Comment