由於 TanStack Query 的資料獲取機制是基於 Promise 不可知論 (Promise-agnostic) 設計的,您實際上可以使用任何非同步資料獲取客戶端,包括瀏覽器原生的 fetch API、graphql-request 等等。
HttpClient 是 Angular 強大且整合完善的一部分,具有以下優勢:
由於 TanStack Query 是基於 Promise 的函式庫,來自 HttpClient 的可觀察物件需轉換為 Promise。這可透過 rxjs 的 lastValueFrom 或 firstValueFrom 函式實現。
@Component({
// ...
})
class ExampleComponent {
private readonly http = inject(HttpClient)
readonly query = injectQuery(() => ({
queryKey: ['repoData'],
queryFn: () =>
lastValueFrom(
this.http.get('https://api.github.com/repos/tanstack/query'),
),
}))
}
@Component({
// ...
})
class ExampleComponent {
private readonly http = inject(HttpClient)
readonly query = injectQuery(() => ({
queryKey: ['repoData'],
queryFn: () =>
lastValueFrom(
this.http.get('https://api.github.com/repos/tanstack/query'),
),
}))
}
由於 Angular 正逐步將 RxJS 改為可選依賴,預計 HttpClient 未來也將支援 Promise。
TanStack Query for Angular 計劃加入對可觀察物件的支援。
資料獲取客戶端 | 優點 | 缺點 |
---|---|---|
Angular HttpClient | 功能豐富且與 Angular 深度整合。 | 需將可觀察物件轉換為 Promise。 |
Fetch | 瀏覽器原生 API,不增加套件體積。 | 功能陽春的 API,缺乏許多進階特性。 |
專用函式庫如 graphql-request | 針對特定使用場景提供專屬功能。 | 若非 Angular 專用函式庫,與框架的整合度較差。 |