Angular Services และ Dependency Injection อธิบายแบบเข้าใจง่าย
#angular12 เม.ย. 2569
Service คืออะไร
ใน Angular Service คือ class ที่ใช้เก็บ business logic, ดึงข้อมูลจาก API หรือแชร์ข้อมูลระหว่าง component โดยไม่ต้องส่งผ่าน Input/Output
สร้าง Service
import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { Observable } from 'rxjs';
@Injectable({
providedIn: 'root' // ทำให้ใช้ได้ทั้ง app
})
export class UserService {
private apiUrl = 'https://api.example.com/users';
constructor(private http: HttpClient) {}
getUsers(): Observable<User[]> {
return this.http.get<User[]>(this.apiUrl);
}
getUserById(id: number): Observable<User> {
return this.http.get<User>(`${this.apiUrl}/${id}`);
}
}
ใช้ Service ใน Component
@Component({
standalone: true,
template: `
<ul>
<li *ngFor="let user of users">{{ user.name }}</li>
</ul>
`
})
export class UserListComponent implements OnInit {
users: User[] = [];
constructor(private userService: UserService) {}
ngOnInit() {
this.userService.getUsers().subscribe(users => {
this.users = users;
});
}
}
Dependency Injection (DI)
Angular ใช้ DI pattern ในการ inject service เข้า component โดยอัตโนมัติ
// inject() function (Angular 14+)
import { inject } from '@angular/core';
export class UserListComponent {
private userService = inject(UserService);
private router = inject(Router);
}
Scope ของ Service
// Root scope - instance เดียวทั้ง app
@Injectable({ providedIn: 'root' })
// Component scope - instance ใหม่ทุกครั้ง
@Component({
providers: [UserService]
})
สรุป
Service + DI เป็นหัวใจของ Angular architecture ช่วยให้โค้ด reusable, testable และแยก concern ได้ชัดเจนครับ