ခဏလေး ဒီလိုပဲ စဉ်းစားကြည့်
Part 1 မှာ ဆောက်ထားတဲ့ structure ပေါ်မှာ Part 2 မှာတော့ app ရဲ့ core feature ဖြစ်တဲ့ task add/list/toggle functionality ကို ထည့်သွားမှာပါ။ Service, dependency injection, reactive forms, *ngFor directive နဲ့ two-way binding lesson တွေက ဒီအဆင့်အတွက် အခြေခံအားလုံးဖြစ်ပါတယ်။ Component တွေအကြား data ကို share လုပ်ဖို့ TaskService တစ်ခု ဗဟိုချုပ်ကိုင်ပြီး BehaviorSubject နဲ့ task list ကို manage လုပ်သွားမှာဖြစ်ပါတယ်။ ဒီလိုလုပ်ခြင်းအားဖြင့် component logic တွေ ရိုးရှင်းပြီး reusable ဖြစ်လာပါတယ်။
လက်တွေ့ ဆောက်ကြည့်မယ်
`TaskService` ကို `ng generate service task` နဲ့ ဆောက်ပြီး internal BehaviorSubject<Task[]> တစ်ခုနဲ့ `getTasks()`, `addTask(task)`, `toggleComplete(id)` method သုံးခု implement လုပ်ပါ။ TaskListComponent မှာ FormGroup (title, description) တစ်ခုနဲ့ new task ထည့်ရန် form တည်ဆောက်ပြီး submit ဖြစ်ရင် service.addTask() ခေါ်ပါ။ Task list ကို *ngFor နဲ့ loop ပြီး checkbox တစ်ခုစီအတွက် [(ngModel)] နဲ့ completed status ကို toggle လုပ်နိုင်အောင် ချိတ်ဆက်ပါ။ Completed task တွေကို ngClass နဲ့ strikethrough style ပေးပါ။
Code နမူနာ
// task.service.ts
import { Injectable } from '@angular/core';
import { BehaviorSubject } from 'rxjs';
import { Task } from './task.model';
@Injectable({ providedIn: 'root' })
export class TaskService {
private tasksSubject = new BehaviorSubject<Task[]>([]);
tasks$ = this.tasksSubject.asObservable();
private nextId = 1;
getTasks() {
return this.tasks$;
}
addTask(title: string, description: string) {
const current = this.tasksSubject.value;
const newTask: Task = { id: this.nextId++, title, description, completed: false };
this.tasksSubject.next([...current, newTask]);
}
toggleComplete(id: number) {
const updated = this.tasksSubject.value.map(t =>
t.id === id ? { ...t, completed: !t.completed } : t
);
this.tasksSubject.next(updated);
}
}Form ကနေ task title/description ရိုက်ပြီး submit လုပ်ရင် list ထဲမှာ task အသစ်တစ်ခု ချက်ချင်းပေါ်လာပြီး checkbox click လုပ်ရင် strikethrough style ပြောင်းသွားမှာဖြစ်သည်။၅ မိနစ် စမ်းကြည့်
5 minutes အတွင်း TaskService ထဲမှာ deleteTask(id) method တစ်ခု ထပ်ထည့်ပြီး TaskListComponent ကနေ delete button နဲ့ ခေါ်သုံးကြည့်ပါ။
သတိလေးတစ်ချက်
Service state ကို component ထဲမှာ တိုက်ရိုက် mutate မလုပ်ဘဲ Subject.next() နဲ့ new reference ပြန်ပေးရင် change detection မှန်ကန်စွာ အလုပ်လုပ်ပါလိမ့်မယ်။