Lädt...

🔧 Mastering Angular's Resource API - A Practical Guide


Nachrichtenbereich: 🔧 Programmierung
🔗 Quelle: dev.to

Angular 19 introduced the Resource API, and with the latest updates, we now have rxResource, a powerful way to handle data fetching in Angular applications. If you’ve been working with RxJS-based data streams, signals, and API calls, this blog will show you how rxResource simplifies your code while improving efficiency.

🔹 What is rxResource?

rxResource is part of the Angular Core RxJS Interop package, which allows developers to fetch and manage API data in a more reactive, declarative, and efficient way. It:

✅ Integrates seamlessly with signals

✅ Automatically tracks state (loading, success, error)

✅ Works with RxJS streams and Angular's HttpClient

✅ Reduces the need for manual subscriptions

🔹 Setting Up rxResource in an Angular App

Project Structure

Here's a glimpse of our Angular project using rxResource:

angular-examples/
│── src/
│   ├── app/
│   │   ├── app.component.ts
│   │   ├── app.component.html
│   │   ├── app.component.css
│   │   ├── app.config.ts
│   │   ├── app.routes.ts
│── package.json
│── angular.json
│── tsconfig.json
│── README.md

🔹 Implementing rxResource for API Calls

Let’s create a simple comment-fetching app using rxResource to retrieve data dynamically from an API.

1️⃣ Define the Component with rxResource

import { HttpClient } from '@angular/common/http';
import { Component, computed, inject, signal } from '@angular/core';
import { rxResource } from '@angular/core/rxjs-interop';

interface Comment {
  postId: number;
  id: number;
  name: string;
  email: string;
  body: string;
}

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrl: './app.component.css',
})
export class AppComponent {
  title = 'angular-examples';

  // Signal to track the current Post ID
  postId = signal(1);

  // Inject HttpClient for API requests
  http = inject(HttpClient);

  // Fetch comments using rxResource
  comments = rxResource({
    request: this.postId,
    loader: (request) =>
      this.http.get<Comment[]>(
        `https://jsonplaceholder.typicode.com/comments?postId=${request.request}`
      ),
  });

  // Update the Post ID dynamically
  updatePostId(event: any) {
    const newValue = parseInt(event.target.value, 10);
    if (!isNaN(newValue) && newValue > 0) {
      this.postId.set(newValue);
    }
  }

  // Navigate between posts
  nextPost() {
    this.postId.update((current) => current + 1);
  }

  previousPost() {
    if (this.postId() > 1) {
      this.postId.update((current) => current - 1);
    }
  }

  // Compute the email of the first comment
  firstCommentEmail = computed(() => {
    return this.comments.value()?.[0]?.email ?? 'No comments available';
  });
}

🔹 Handling UI State with rxResource

The Resource API automatically manages loading, success, and error states. Here’s how we display them in our UI using Angular's control flow syntax (@if, @for):

<div class="container">
  <div class="input-container">
    <label for="postIdInput" class="input-label">Post ID:</label>
    <input type="number" id="postIdInput" [value]="postId()" (input)="updatePostId($event)" class="post-id-input" />
  </div>

  @if (comments.isLoading()) {
    <p class="loading-message">Loading comments...</p>
  } @else if (comments.error()) {
    <p class="error-message">Error: {{ comments.error() }}</p>
  } @else if (comments.hasValue()) {
    <p class="total-comments">Total Comments: {{ comments.value().length }}</p>
    <ul class="comment-list">
      @for (comment of comments.value(); track comment.id) {
        <li class="comment-item">
          <strong>{{ comment.name }}</strong> ({{ comment.email }}):<br />
          <span>{{ comment.body }}</span>
        </li>
      }
    </ul>
    <button (click)="comments.reload()" class="refresh-button">Refresh</button>
  }

  <div class="navigation-container">
    <button (click)="previousPost()" [disabled]="postId() <= 1" class="nav-button">Previous Post</button>
    <button (click)="nextPost()" class="nav-button">Next Post</button>
    <p class="current-post">Current Post ID: {{ postId() }}</p>
  </div>

  <div class="first-email-container">
    <p>First comment email: {{ firstCommentEmail() }}</p>
  </div>
</div>

🔹 Benefits of Using rxResource

Automatic State Handling

  • rxResource automatically tracks loading, success, and error states, removing the need for manual handling.

Better Performance

  • It caches API responses and minimizes redundant requests, reducing network calls.

Cleaner Code

  • No need to manually handle RxJS subscriptions, reducing complexity.

Seamless Integration with Signals

  • Works perfectly with Angular signals, making reactivity easier.

🔹 Configuring HttpClient for rxResource

Since rxResource relies on HttpClient, we need to provide it in the app.config.ts file:

import { ApplicationConfig, provideZoneChangeDetection } from '@angular/core';
import { provideRouter } from '@angular/router';
import { provideHttpClient } from '@angular/common/http';

export const appConfig: ApplicationConfig = {
  providers: [
    provideZoneChangeDetection({ eventCoalescing: true }),
    provideRouter([]),
    provideHttpClient(), // Ensure HttpClient is available
  ],
};

🔹 Running the Project

To try out rxResource in AngularExamples, follow these steps:

1️⃣ Clone the Repository:

git clone https://github.com/manthanank/angular-examples.git
cd angular-examples

2️⃣ Checkout to rxresource Branch:

git checkout rxresource

3️⃣ Install Dependencies:

npm install

4️⃣ Run the Development Server:

ng serve

Now, open your browser and go to http://localhost:4200/. 🎉

🔹 Conclusion

The rxResource API is a game-changer for data fetching in Angular applications. It reduces boilerplate code, improves performance, and integrates seamlessly with signals and RxJS streams.

Exploring the Code

Visit the GitHub repository to explore the code in detail.

Live Demo

Check out the working example on StackBlitz

Additional Resources

Feel free to leave comments or questions below! 👋

...

🔧 Mastering Angular's Resource API - A Practical Guide


📈 40.95 Punkte
🔧 Programmierung

🔧 🚀 Mastering Angular 17+ Fundamentals : A Dev’s Guide to Modern Angular


📈 28.96 Punkte
🔧 Programmierung

🔧 A Comprehensive Guide to the Angular Roadmap: Mastering Angular in 2024


📈 28.96 Punkte
🔧 Programmierung

🔧 Building Reactive UIs with Angular Signals: A Practical Profile Editor (Angular 19)


📈 27.29 Punkte
🔧 Programmierung

🔧 Comparing Radix Angular and Angular CDK: A Practical Perspective


📈 27.29 Punkte
🔧 Programmierung

🔧 Angular Addicts #36: Angular 19.2, Angular week at Nx, Accessibility testing &amp; more


📈 26.73 Punkte
🔧 Programmierung

🔧 Angular Addicts #34: Angular 19.1, AI &amp; Angular, introduction to DDD &amp; more


📈 26.73 Punkte
🔧 Programmierung

🔧 How to upgrade your Angular web project from Angular V13 to Angular V17


📈 26.73 Punkte
🔧 Programmierung

🕵️ CVE-2023-26116 | angular angular.copy redos (SNYK-JS-ANGULAR-3373044)


📈 26.73 Punkte
🕵️ Sicherheitslücken

🔧 Mastering CSS BEM naming with Practical Examples: Pure HTML, Angular, and Next.js


📈 25.45 Punkte
🔧 Programmierung

🔧 Mastering RESTful API Design: A Practical Guide


📈 25.29 Punkte
🔧 Programmierung

🔧 Streamlining API Calls in Angular v18 with TanStack Angular Query


📈 22.49 Punkte
🔧 Programmierung

🔧 Angular View Encapsulation - A Practical Guide to Component Styling


📈 22.45 Punkte
🔧 Programmierung

🔧 A Practical guide to building cross-platform apps with Angular, Ionic, Capacitor, and Nx


📈 22.45 Punkte
🔧 Programmierung

🔧 Angular Addicts #32: Angular 19, new Style guide RFC &amp; more


📈 21.89 Punkte
🔧 Programmierung

🔧 Angular Addicts #28: Angular 18.1 (w. the new @let syntax), Component testing, SSR guide &amp; more


📈 21.89 Punkte
🔧 Programmierung

📰 ANGULAR 6 (FORMERLY ANGULAR 2) – THE COMPLETE GUIDE


📈 21.89 Punkte
📰 Alle Kategorien

🔧 Flexible Angular Builds: A Guide to Angular 19 Build-Time Variables with Docker


📈 21.89 Punkte
🔧 Programmierung

🔧 Mastering Azure API Management Policies with 3 Practical Cases


📈 21.22 Punkte
🔧 Programmierung

🔧 Mastering HTTP: A Practical Guide for Developers &amp; Cybersecurity Enthusiasts


📈 20.61 Punkte
🔧 Programmierung

🔧 Mastering TypeScript Interfaces: A Comprehensive Guide with Practical Examples


📈 20.61 Punkte
🔧 Programmierung

🔧 Mastering HTTP: A Practical Guide for Developers &amp; Cybersecurity Enthusiasts


📈 20.61 Punkte
🔧 Programmierung

🔧 Mastering CORS: The Definitive Guide with Practical Examples


📈 20.61 Punkte
🔧 Programmierung

🔧 Mastering Azure SQL Database: A Practical Guide to SSMS Integration


📈 20.61 Punkte
🔧 Programmierung

🔧 Mastering CORS: The Definitive Guide with Practical Examples


📈 20.61 Punkte
🔧 Programmierung

🔧 Mastering Scheduled Tasks in GoFrame: A Practical Guide


📈 20.61 Punkte
🔧 Programmierung

🔧 Mastering C# Switch Expressions and Pattern Matching: A Practical Guide


📈 20.61 Punkte
🔧 Programmierung

🔧 Mastering Text Generation with OpenAI: A Practical Guide to Parameters and Settings


📈 20.61 Punkte
🔧 Programmierung

🔧 Mastering Content Security Policy (CSP) for JavaScript Applications: A Practical Guide


📈 20.61 Punkte
🔧 Programmierung

🔧 Mastering Go: A Practical Guide to Modern Golang Development


📈 20.61 Punkte
🔧 Programmierung

🔧 Mastering SOLID Principles in Java: A Practical Guide


📈 20.61 Punkte
🔧 Programmierung

matomo