| id | Angular-HttpClient-and-other-data-fetching-clients |
|---|---|
| title | Angular HttpClient and other data fetching clients |
Because TanStack Query's fetching mechanisms are agnostically built on Promises, you can use literally any asynchronous data fetching client, including the browser native fetch API, graphql-request, and more.
HttpClient is a powerful and integrated part of Angular, which gives the following benefits:
- Mock responses in unit tests using provideHttpClientTesting.
- Interceptors can be used for a wide range of functionality including adding authentication headers, performing logging, etc. While some data fetching libraries have their own interceptor system,
HttpClientinterceptors are integrated with Angular's dependency injection system. HttpClientautomatically informsPendingTasks, which enables Angular to be aware of pending requests. Unit tests and SSR can use the resulting application stableness information to wait for pending requests to finish. This makes unit testing much easier for Zoneless applications.- When using SSR,
HttpClientwill cache requests performed on the server. TanStack Query will additionally hydrate its cache from the server-rendered HTML when you useprovideTanStackQuery.
As TanStack Query is a promise based library, observables from HttpClient need to be converted to promises. This can be done with the lastValueFrom or firstValueFrom functions from rxjs.
@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'),
),
}))
}Since Angular is moving towards RxJS as an optional dependency, it's expected that
HttpClientwill also support promises in the future.
| Data fetching client | Pros | Cons |
|---|---|---|
| Angular HttpClient | Featureful and very well integrated with Angular. | Observables need to be converted to Promises. |
| Fetch | Browser native API, so adds nothing to bundle size. | Barebones API which lacks many features. |
Specialized libraries such as graphql-request |
Specialized features for specific use cases. | If it's not an Angular library it won't integrate well with the framework. |