Home >Web Front-end >JS Tutorial >Streamlining API Calls in Angular vwith TanStack Angular Query

Streamlining API Calls in Angular vwith TanStack Angular Query

Linda Hamilton
Linda HamiltonOriginal
2024-10-24 00:08:29770browse

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.

npm install @tanstack/query-angular-experimental @tanstack/angular-query-devtools-experimental 

3. Define a Service repos.service.ts to consume API call:

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)
  ]
};

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.

export type Response = {
  name: string
  description: string
  subscribers_count: number
  stargazers_count: number
  forks_count: number
}

5. Let’s render the data in component UI github-repo-list.component.html:

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`);
  }
}
  • 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:

Streamlining API Calls in Angular vwith TanStack Angular Query

Checkout complete source code at Github. Thanks ?

The above is the detailed content of Streamlining API Calls in Angular vwith TanStack Angular Query. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn