28. إدارة طلبات PUT/DELETE
1. طلبات PUT (التحديث)
تُستخدم طلبات PUT لتحديث مورد بأكمله على الخادم. على غرار POST، تتطلب حمولة (البيانات المحدثة) وعادةً ما تتضمن معرّف المورد (ID) في مسار العنوان (URL path).
typescript // data.service.ts
updatePost(id: number, updatedData: Partial${this.baseUrl}/posts/${id};
// يتطلب HttpClient.put() المعرّف في العنوان وحمولة التحديث
return this.http.put
في المكون، تشترك وغالباً لا تحتاج إلى الكائن المُعاد، بل تحتاج فقط إلى تأكيد النجاح.
typescript
// component.ts
updateExistingPost(id: number) {
const patch = { title: 'Updated Title' };
this.dataService.updatePost(id, patch).subscribe(() => {
console.log(Post ${id} updated.);
});
}
2. طلبات DELETE (الحذف)
تزيل طلبات DELETE مورداً. تتطلب فقط معرّف المورد (ID) في العنوان وعادةً لا تتطلب جسماً (body).
typescript // data.service.ts
deletePost(id: number) {
const url = ${this.baseUrl}/posts/${id};
// نوع الاستجابة غالباً ما يكون void أو كائناً فارغاً {}
return this.http.delete
في المكون:
typescript
// component.ts
deleteItem(id: number) {
this.dataService.deletePost(id).subscribe({
next: () => {
alert(Post ${id} successfully deleted.);
// تحديث القائمة محلياً
},
error: (e) => {
console.error('Failed to delete:', e);
}
});
}