
การ call api ใน angular
เรามาดูตัวอย่างการ call api ใน angular กันครับ
ใน angular นั้นเราสามารถ call api ได้หลายแบบ ตัวอย่างนี้เราจะใช้ HttpClient module เพื่อ call api ซึ่งสามารถใช้ได้ทั้ง get, post, put, และ delete
ตัวอย่างโค้ด
- import module ที่เราจำเป็นต้องใช้ก่อน ซึ่งเราจะสร้างใน service
import { HttpClient } from '@angular/common/http';
import { Injectable } from '@angular/core';
- inject HttpClient module ใน constructor
@Injectable({
providedIn: 'root'
})
export class MyService {
constructor(private http: HttpClient) {}
}
- เราจะใช้ http.get() เพื่อ request api และ subscribe เพื่อ return Observable
export class MyService {
...
getData() {
return this.http.get<any>('https://api.example.com/data').subscribe(data => {
console.log(data);
});
}
}
- เราสามารถใช้ http.post(), http.put(), และ http.delete() ได้ตามตัวอย่าง
export class MyService {
...
postData(data) {
return this.http.post<any>('https://api.example.com/data', data).subscribe(response => {
console.log(response);
});
}
putData(data) {
return this.http.put<any>('https://api.example.com/data', data).subscribe(response => {
console.log(response);
});
}
deleteData(id) {
return this.http.delete<any>('https://api.example.com/data/'+ id).subscribe(response => {
console.log(response);
});
}
}
ในการจัดการกับ error เราสามารถใช้ catchError เพื่อดักจับ error ได้
import { catchError } from 'rxjs/operators';
export class MyService {
...
getData() {
return this.http.get<any>('https://api.example.com/data')
.pipe(catchError(this.handleError));
}
private handleError(error: HttpErrorResponse) {
if (error.error instanceof ErrorEvent) {
// A client-side or network error occurred. Handle it accordingly.
console.error('An error occurred:', error.error.message);
} else {
// The backend returned an unsuccessful response code.
// The response body may contain clues as to what went wrong,
console.error(
`Backend returned code ${error.status}, ` +
`body was: ${error.error}`);
}
// return an observable with a user-facing error message
return throwError(
'Something bad happened; please try again later.');
};
}