


Angular - Streamlining Data Retrieval with Experimental Resource and rxResource APIs
Angular 19 introduces two exciting experimental APIs, resource and rxResource, designed to simplify asynchronous data retrieval and management. This article explores these APIs, diving into their functionalities and showcasing how they enhance developer experience (DX) for crafting reactive and efficient Angular applications. All API endpoints used in the article are from JSON Placeholder.
Born from a Vision: Asynchronous Data Loading with Signals
The idea behind these APIs originated from a pull request by Alex Rickabaugh. The core concept lies in utilizing Signals to manage the asynchronous loading of resources. While resource utilizes Promises, rxResource leverages Observables, catering to different developer preferences. Both APIs provide a WritableResource object, allowing you to update resource data locally.
A resource offers several signals to keep you informed about its state:
- Value: Provides the current data of the resource, representing the result of a query.
- Status: Reflects the resource's current state. Here's a breakdown of the various status types:
- Error: Provides details on errors encountered during data retrieval.
Creating a Resource
Instantiating a resource is simple:
This will result the following output. Notice how initially the status is "Loading" (2) and eventually it becomes "Resolved" (4).
Updating Resource Data Locally
To update a resource's data locally, leverage the update() method of the value signal. See the following template and component for reference:
The updateResource() function will update the value of resource locally with a different string.
This will produce the following output. Notice the status being "Local" (5) as it's value has been updated locally.
Refreshing a Resource
Let's create a Refresh button in our template and refresh a resource when the user clicks it.
The reload function in the code below triggers the resource loader to execute again. If user clicks Refresh button multiple times, the loader will be triggered only once until the previous request is finished. It is similar to exhaustMap in Rxjs.
Notice the status transitioning from "Reloading" (3) to "Resolved" (4) in the output below.
Data Based on Signals: Dynamic Resource Loading
Suppose you want to fetch posts based on an postId signal. You can achieve this by passing the signal as a request parameter to your endpoint:
By passing the signal postId as a request parameter, you can achieve dynamic data retrieval based on the postId value. Here's an example:
This will result in the following output:
While this approach works for initial data fetching, it lacks reactivity. Loaders in Angular's resource API are inherently untracked. This means that if a signal like postId changes after the initial resource creation, the loader won't automatically re-execute.
To overcome this limitation and ensure reactive behavior, we need to explicitly bind the signal to the resource's request parameter. This establishes a dependency between the resource and the signal, ensuring that the loader is triggered whenever the signal's value changes.
Let's create a button to update the signal postId to a random number.
Now, in the component, we add a method to update the signal postId to a random number. We also bind postId to the request parameter of our resource to ensure reactivity.
Handling Local Data Changes During Active Requests
When a local data change occurs while a resource is fetching data from a remote source, a potential race condition arises. To mitigate this, we can leverage the abortSignal() function to gracefully handle concurrent requests.
By providing an AbortSignal object to the resource's loader function, we can cancel ongoing requests if the signal is aborted. This is particularly useful when a new request is triggered before the previous one completes.
Here's a breakdown of the process:
- Local Data Change: A user modifies data locally, triggering a new request.
- Abort Signal: An AbortSignal is created and passed to the resource's loader.
- Request Cancellation: If the previous request is still in progress, it's canceled using the AbortSignal.
- New Request Initiation: The loader is invoked with the updated postId and the new AbortSignal.
- Data Fetching and Update: The new request proceeds, and the resource's value is updated with the fetched data.
Here's an example which will fetch data based on new value of signal and cancel the previous request in progress in case of multiple triggers.
Multiple Signal Dependencies: Reactive Resource Loading
A resource can be made reactive to changes in multiple signals, allowing for complex data fetching scenarios. By binding multiple signals to the resource's request parameter, the loader will be triggered whenever any of the dependent signals change.
Here's an example demonstrating this behavior where both postId and userId are being set by a random number and the resource is made reactive to changes in both the signals:
In the above example, the loader will be re-executed whenever either the userId or postId signal changes. This ensures that the resource always reflects the latest data based on the current values of its dependent signals.
Code Reusability with Resource Functions
To enhance code maintainability and promote a modular approach, consider creating reusable resource functions. These functions encapsulate the logic for creating resources with specific configurations, making them easily shareable across your application.
Here's an example of a reusable resource function:
In the example above, myResource can be used across different areas of your application, ensuring clean code and reusability.
RxResource: Leveraging Observables for Reactive Data Fetching
When working with Observables in your Angular application, the rxResource API provides a powerful mechanism for managing asynchronous data operations. Similar to the resource API, rxResource allows you to define resources that fetch data and emit it as an Observable.
Key Differences from resource:
- Observable-Based: rxResource leverages Observables to provide a stream of data, enabling more flexible and reactive data handling.
- No abortSignal: Since Observables can be easily unsubscribed, there's no need for an explicit abortSignal to cancel requests.
- First-Value-Only: The current implementation of rxResource only considers the first emitted value from the Observable. Subsequent emissions are ignored.
- Writable Resources: Like resource, rxResource allows you to update the local state of a resource using Observables.
Here's an example of a resource created using rxResource:
In this example, the loader will emit the posts as an Observable. You can subscribe to this Observable to react to data changes and perform necessary actions.
Conclusion
Angular's resource and rxResource APIs represent a significant step forward in simplifying asynchronous data operations. These APIs offer a declarative and concise approach to fetching and managing data, enhancing developer productivity and application performance.
While still in developer preview, these APIs hold the promise of revolutionizing the way Angular developers handle data retrieval. By leveraging Signals and Observables, these APIs provide a flexible and efficient mechanism for managing data flow and reactivity in Angular applications.
Github PR: https://github.com/angular/angular/pull/58255
Code repository: https://github.com/Ingila185/angular-resource-demo
Stackblitz Playground: https://stackblitz.com/edit/stackblitz-starters-hamcfa?file=src/main.ts
The above is the detailed content of Angular - Streamlining Data Retrieval with Experimental Resource and rxResource APIs. For more information, please follow other related articles on the PHP Chinese website!

JavaScript core data types are consistent in browsers and Node.js, but are handled differently from the extra types. 1) The global object is window in the browser and global in Node.js. 2) Node.js' unique Buffer object, used to process binary data. 3) There are also differences in performance and time processing, and the code needs to be adjusted according to the environment.

JavaScriptusestwotypesofcomments:single-line(//)andmulti-line(//).1)Use//forquicknotesorsingle-lineexplanations.2)Use//forlongerexplanationsorcommentingoutblocksofcode.Commentsshouldexplainthe'why',notthe'what',andbeplacedabovetherelevantcodeforclari

The main difference between Python and JavaScript is the type system and application scenarios. 1. Python uses dynamic types, suitable for scientific computing and data analysis. 2. JavaScript adopts weak types and is widely used in front-end and full-stack development. The two have their own advantages in asynchronous programming and performance optimization, and should be decided according to project requirements when choosing.

Whether to choose Python or JavaScript depends on the project type: 1) Choose Python for data science and automation tasks; 2) Choose JavaScript for front-end and full-stack development. Python is favored for its powerful library in data processing and automation, while JavaScript is indispensable for its advantages in web interaction and full-stack development.

Python and JavaScript each have their own advantages, and the choice depends on project needs and personal preferences. 1. Python is easy to learn, with concise syntax, suitable for data science and back-end development, but has a slow execution speed. 2. JavaScript is everywhere in front-end development and has strong asynchronous programming capabilities. Node.js makes it suitable for full-stack development, but the syntax may be complex and error-prone.

JavaScriptisnotbuiltonCorC ;it'saninterpretedlanguagethatrunsonenginesoftenwritteninC .1)JavaScriptwasdesignedasalightweight,interpretedlanguageforwebbrowsers.2)EnginesevolvedfromsimpleinterpreterstoJITcompilers,typicallyinC ,improvingperformance.

JavaScript can be used for front-end and back-end development. The front-end enhances the user experience through DOM operations, and the back-end handles server tasks through Node.js. 1. Front-end example: Change the content of the web page text. 2. Backend example: Create a Node.js server.

Choosing Python or JavaScript should be based on career development, learning curve and ecosystem: 1) Career development: Python is suitable for data science and back-end development, while JavaScript is suitable for front-end and full-stack development. 2) Learning curve: Python syntax is concise and suitable for beginners; JavaScript syntax is flexible. 3) Ecosystem: Python has rich scientific computing libraries, and JavaScript has a powerful front-end framework.


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

DVWA
Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software

EditPlus Chinese cracked version
Small size, syntax highlighting, does not support code prompt function

Zend Studio 13.0.1
Powerful PHP integrated development environment

VSCode Windows 64-bit Download
A free and powerful IDE editor launched by Microsoft

Dreamweaver Mac version
Visual web development tools
