Streamlining API Calls in Angular v18 with TanStack Angular Query
Muhammad Awais
Posted on October 23, 2024
This article provides guidance on using the stable @tanstack/query-angular
package in Angular v18 projects for efficient API calling 🚀
Managing API interactions in Angular projects often involves repetitive logic, leading to code duplication, increased maintenance burden, and potential state management complexities. While @tanstack/angular-query-experimentaloffers a robust solution, it's important to note that this package is still under experimental development. Instead, for Angular v17 projects specifically, consider utilizing the stable @tanstack/angular-query-experimental package.
Key Benefits of TanStack Angular Query:
Declarative Approach: Define query functions that encapsulate API requests and associated data processing, promoting clean and readable code.
Automatic Caching and Refetching: Leverage built-in caching strategies like “stale-while-revalidate” to optimize performance and reduce unnecessary server calls. Implement data refetching based on your needs (e.g., data staleness or window refocus) for enhanced data consistency.
Reactive Data Handling: Access and manage data using observables and signals, enabling reactive updates in UI components without manual lifecycle hooks or complex state management patterns.
Modular Design: Organize API logic into reusable query entities, promoting code organization and maintainability.
Dedicated Devtools: Gain insights into query execution, cache state, and refetching patterns through the TanStack Query Devtools, facilitating debugging and optimization.
Installation:
Install the necessary packages using npm or yarn:
npm install @tanstack/query-angular-experimental @tanstack/angular-query-devtools-experimental
Step by Step Implementation:
While @tanstack/angular-query-experimental is available for Angular v17, it's currently under experimental development and not recommended for production use. For stable and reliable API call management in Angular v17 projects, consider using the stable @tanstack/query-angular package.
Here's a step-by-step implementation guide:
1. Add Providers in app.config.ts:
import { ApplicationConfig } from '@angular/core';
import { provideRouter } from '@angular/router';
import { routes } from './app.routes';
import { provideHttpClient } from '@angular/common/http';
import { QueryClient, provideAngularQuery } from '@tanstack/angular-query-experimental';
const queryClient = new QueryClient();
export const appConfig: ApplicationConfig = {
providers: [
provideRouter(routes),
provideHttpClient(),
provideAngularQuery(queryClient)
]
};
- Importing provideHttpClient, QueryClient, provideAngularQuery.
- Defining and exporting the app configuration object by providing routing, HTTP, and Angular Query functionality through dependency injection.
2. Define a Typescript based Type for API response:
Types are used in TypeScript to specify the structure and type of data, aiding in code organization and error prevention. Within your Angular application, this type likely serves as a blueprint for structuring data retrieved from an API or other data source.
export type Response = {
name: string
description: string
subscribers_count: number
stargazers_count: number
forks_count: number
}
3. Define a Service repos.service.ts to consume API call:
import { HttpClient } from '@angular/common/http';
import { Injectable } from '@angular/core';
import { Response } from '../../types/responce.type';
@Injectable({
providedIn: 'root'
})
export class ReposService {
endpoint: string = 'https://api.github.com';
constructor(
private http: HttpClient
) { }
getRepos() {
return this.http.get<Response>(`${this.endpoint}/repos/tanstack/query`);
}
}
The service is responsible for making HTTP requests to the GitHub API to fetch repository data. It uses the HttpClient to make the requests and expects the response data to conform to the structure defined in the Response type.
4. Initiate Angular Query in the Component github-repo-list.component.ts:
Component uses Angular Query to manage data fetching and caching. It injects the ReposService to make API calls. It defines a query with the unique key 'repoData' to fetch repository data using the queryFn.
import { ChangeDetectionStrategy, Component, inject } from '@angular/core';
import { injectQuery } from '@tanstack/angular-query-experimental';
import { AngularQueryDevtools } from '@tanstack/angular-query-devtools-experimental';
import { lastValueFrom } from 'rxjs';
import { ReposService } from '../services/repos/repos.service';
@Component({
selector: 'app-github-repo-list',
standalone: true,
changeDetection: ChangeDetectionStrategy.OnPush,
imports: [AngularQueryDevtools],
templateUrl: './github-repo-list.component.html',
styleUrl: './github-repo-list.component.scss'
})
export class GithubRepoListComponent{
reposService = inject(ReposService);
query = injectQuery(() => ({
queryKey: ['repoData'],
queryFn: () =>
lastValueFrom(
this.reposService.getRepos()
),
}))
}
5. Let’s render the data in component UI github-repo-list.component.html:
@if (query.isPending()) {
Loading...
}
@if (query.error()) {
An error has occurred: {{ query.error()?.message }}
}
@if (query.data(); as data) {
<h1>Name: {{ data.name }}</h1>
<p>Description: {{ data.description }}</p>
<strong>👀 {{ data.subscribers_count }}</strong>
<strong>✨ {{ data.stargazers_count }}</strong>
<strong>🍴 {{ data.forks_count }}</strong>
}
<angular-query-devtools initialIsOpen />
- This template conditionally renders different content based on the query’s state: loading, error, or success.
- It effectively handles different scenarios, providing appropriate feedback to the user.
- It incorporates Angular Query devtools for debugging and inspection.
Working Demo:
Checkout complete source code at Github. Thanks 😊
Posted on October 23, 2024
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.