DEV Community

Nhan Nguyen
Nhan Nguyen

Posted on

Exploring Angular v19 Resource API

The introduction of the Resource API in Angular v19 marks a significant step forward in managing asynchronous data fetching and state in Angular applications. Designed to simplify the developer experience, this new feature is still experimental but shows great promise for modern Angular projects.

In this blog post, we'll explore the key features, benefits, drawbacks, and sample implementations of the Resource API.

What is the Resource API?

The Resource API provides a declarative and reactive way to manage asynchronous data operations. It builds upon Angular’s new Signals system, offering two primary functions:

  • resource(): A promise-based approach for handling asynchronous data fetching.

  • rxResource(): An Observable-based approach aligning with Angular’s existing RxJS ecosystem.

These functions allow developers to define loaders and reactive signals for state management, providing built-in support for loading, error, and data states.

Key Features

  • Declarative Syntax: Simplifies code readability and maintainability.

  • Built-in State Management: Automatically tracks loading, success, and error states.

  • Reactive Integration: Seamlessly integrates with Angular Signals and RxJS Observables.

  • Manual Control: Offers methods like reload() and update() for flexible state updates.

Pros

  • Improved Readability: The declarative approach reduces boilerplate code.

  • Reactive Design: Works well with Angular Signals and RxJS for real-time updates.

  • State Tracking: Built-in support for common states like isLoading, value, and error.

  • Flexibility: Methods like reload() provide granular control over data loading.

  • Future-Proofing: Experimental status allows developers to shape its evolution.

Cons

  • Experimental Nature: Not production-ready and subject to breaking changes.

  • Limited Use Cases: Focused on GET requests; lacks built-in support for POST, PUT, DELETE operations.

  • Learning Curve: Requires understanding of Angular Signals and RxJS.
    Performance Considerations: Misuse in frequent state changes can lead to inefficiencies.

  • Early Ecosystem: Sparse community resources and documentation.

Sample Code Implementations

  • Fetching Data with resource()
import { Component, signal } from '@angular/core';
import { resource } from '@angular/core';

@Component({
  selector: 'app-user-list',
  template: `
    <div *ngIf="users.isLoading()">Loading...</div>
    <div *ngIf="users.error()">Error: {{ users.error() }}</div>
    <ul *ngIf="users.value()">
      <li *ngFor="let user of users.value()">{{ user.name }}</li>
    </ul>
    <button (click)="reloadUsers()">Reload</button>
  `,
})
export class UserListComponent {
  users = resource({
    loader: async () => {
      const response = await fetch('https://jsonplaceholder.typicode.com/users');
      if (!response.ok) {
        throw new Error('Failed to fetch users');
      }
      return response.json();
    },
  });

  reloadUsers() {
    this.users.reload();
  }
}
Enter fullscreen mode Exit fullscreen mode
  • Using rxResource() with RxJS Observables:
import { Component, signal } from '@angular/core';
import { rxResource } from '@angular/core';
import { of, delay } from 'rxjs';

@Component({
  selector: 'app-weather',
  template: `
    <div *ngIf="weather.isLoading()">Loading weather...</div>
    <div *ngIf="weather.error()">Error: {{ weather.error() }}</div>
    <div *ngIf="weather.value()">
      <h3>Weather Data:</h3>
      <pre>{{ weather.value() | json }}</pre>
    </div>
    <button (click)="reloadWeather()">Reload Weather</button>
  `,
})
export class WeatherComponent {
  weather = rxResource({
    loader: () =>
      of({
        temperature: Math.floor(Math.random() * 30) + 10,
        condition: 'Sunny',
      }).pipe(delay(1000)),
  });

  reloadWeather() {
    this.weather.reload();
  }
}
Enter fullscreen mode Exit fullscreen mode

When Should You Use the Resource API?

The Resource API is ideal for:

  • Applications heavily reliant on real-time or reactive data.

  • Scenarios where managing multiple states (loading, error, success) is tedious.

  • Developers looking to future-proof their apps with experimental features.

However, the traditional Angular HTTP Client may still be a better fit for more straightforward projects or those requiring immediate production readiness.

Conclusion

The Angular v19 Resource API is a powerful tool for managing asynchronous data in a declarative and reactive manner. While it’s still experimental, it can become a cornerstone of Angular's state management in future versions. If you're an Angular developer, now is a great time to experiment with the Resource API, provide feedback to the Angular team, and stay ahead of the curve.

For detailed documentation, check out the official Angular Resource API Guide.


Feel free to comment below with your thoughts or share your experiences using the Resource API! 🚀

I hope you found it helpful. Thanks for reading. 🙏
Let's get connected! You can find me on:

Top comments (1)

Collapse
 
spock123 profile image
Lars Rye Jeppesen

I know they're working on PUT/POST/DELETE support ..