angular-http은(는) 무엇을 하나요?
Angular v20+에서 resource(), httpResource(), HttpClient를 사용하여 HTTP 데이터 가져오기를 구현합니다. API 호출, 신호 기반 데이터 로딩, 요청/응답 처리 및 인터셉터에 사용됩니다. 데이터 가져오기, API 통합, 로딩 상태, 오류 처리 또는 Observable 기반 HTTP를 신호 기반 패턴으로 변환할 때 트리거됩니다.
개요
이 스킬은 Angular 애플리케이션에서 HTTP 데이터를 가져오는 최신 접근 방식을 제공합니다. Angular v20+에서 도입된 신호 기반 API인 resource()와 httpResource()를 활용하여 반응형 데이터 흐름을 단순화합니다.
주요 기능
resource(): 신호 기반 비동기 리소스 로더httpResource():resource()의 HTTP 특화 래퍼HttpClient: 기존 Observable 기반 HTTP 클라이언트HttpInterceptorFn: 함수형 인터셉터- 신호 기반 데이터 흐름 (Observable 대체)
사용 예시
1. httpResource() 사용
import { httpResource } from '@angular/common/http';
// 간단한 GET 요청
const userResource = httpResource<User>('/api/user/1');
// 신호로 상태 읽기
console.log(userResource.value()); // 데이터
console.log(userResource.isLoading()); // 로딩 상태
console.log(userResource.error()); // 오류
2. resource() 사용
import { resource } from '@angular/core';
const userResource = resource({
request: () => ({ id: userId() }),
loader: async ({ request }) => {
const response = await fetch(`/api/users/${request.id}`);
return response.json();
},
});
3. HttpClient + 신호 패턴
import { HttpClient } from '@angular/common/http';
import { toSignal } from '@angular/core/rxjs-interop';
class UserService {
private http = inject(HttpClient);
// Observable을 신호로 변환
readonly users = toSignal(
this.http.get<User[]>('/api/users'),
{ initialValue: [] }
);
}
4. 인터셉터 사용
import { HttpInterceptorFn } from '@angular/common/http';
export const authInterceptor: HttpInterceptorFn = (req, next) => {
const authReq = req.clone({
headers: req.headers.set('Authorization', 'Bearer token')
});
return next(authReq);
};
// 애플리케이션 구성
bootstrapApplication(AppComponent, {
providers: [
provideHttpClient(
withInterceptors([authInterceptor]),
withFetch() // fetch API 사용
)
]
});
주요 API 참조
| API | 설명 |
|---|---|
resource() | 신호 기반 비동기 리소스 로더 |
httpResource() | HTTP 특화 리소스 로더 |
HttpClient | Observable 기반 HTTP 클라이언트 |
HttpInterceptorFn | 함수형 인터셉터 |
provideHttpClient() | HTTP 클라이언트 구성 함수 |
모범 사례
- 가능하면
httpResource()를 우선 사용하세요. - 상태 관리를 위해
isLoading,error,value신호를 활용하세요. - 타입 안전성을 위해 제네릭 타입을 명시하세요.
- 인터셉터는 함수형 패턴(
HttpInterceptorFn)을 사용하세요. - 성능 향상을 위해
withFetch()를 활성화하세요.