Angular HttpClient: เรียก API และจัดการ Error อย่างถูกต้อง

#angular12 เม.ย. 2569

HttpClient คืออะไร

HttpClient เป็น service ของ Angular สำหรับเรียก HTTP requests ไปยัง API รองรับ GET, POST, PUT, DELETE และอื่นๆ

ตั้งค่า HttpClient

// main.ts
import { provideHttpClient } from '@angular/common/http';

bootstrapApplication(AppComponent, {
  providers: [provideHttpClient()]
});

GET Request

import { HttpClient } from '@angular/common/http';
import { inject } from '@angular/core';

export class PostService {
  private http = inject(HttpClient);

  getPosts() {
    return this.http.get<Post[]>('https://jsonplaceholder.typicode.com/posts');
  }

  getPost(id: number) {
    return this.http.get<Post>(`https://jsonplaceholder.typicode.com/posts/${id}`);
  }
}

POST Request

createPost(post: Partial<Post>) {
  return this.http.post<Post>(
    'https://jsonplaceholder.typicode.com/posts',
    post
  );
}

จัดการ Error ด้วย catchError

import { catchError, throwError } from 'rxjs';
import { HttpErrorResponse } from '@angular/common/http';

getPosts() {
  return this.http.get<Post[]>('/api/posts').pipe(
    catchError((error: HttpErrorResponse) => {
      if (error.status === 404) {
        return throwError(() => new Error('ไม่พบข้อมูล'));
      }
      if (error.status === 500) {
        return throwError(() => new Error('เซิร์ฟเวอร์มีปัญหา'));
      }
      return throwError(() => error);
    })
  );
}

HTTP Interceptor

ใช้สำหรับเพิ่ม header หรือ token ทุก request

import { HttpInterceptorFn } from '@angular/common/http';

export const authInterceptor: HttpInterceptorFn = (req, next) => {
  const token = localStorage.getItem('token');
  if (token) {
    const authReq = req.clone({
      headers: req.headers.set('Authorization', `Bearer ${token}`)
    });
    return next(authReq);
  }
  return next(req);
};
// main.ts
provideHttpClient(withInterceptors([authInterceptor]))

สรุป

HttpClient ใช้งานง่าย รองรับ TypeScript เต็มรูปแบบ และมี interceptor สำหรับจัดการ request/response แบบ centralized ครับ