Everything you need to know about the resource API
Table of Contents
In v19, Angular will introduce a new API for loading resources. This would allow us to fetch data from an api, know about the status of the request, and update the data locally when needed.
Intro
The resource API is very simple in it's core. Let's see the most simple example of how to use it.
The first thing we can notice is that the resource API uses Promises by default for the loader parameter. The other one is that the resource API will return a WritableResource
We can read the current value of the resource by using the value
status
error
The code above will print the following:
Updating the data locally
Let's see how we can update the data locally.
We can update the data locally by using the update
value
This will print the following:
The 'local' status means that the data was updated locally.
Loading the data
Let's make a proper request to the server. Let's load some todos from the JSONPlaceholder API.
This todosResource
Of course, the todosResource
The code above will print the following:
Refreshing the data
Let's say we want to refresh the data when the user clicks on a button.
The refresh
refresh
Loading specific date based on other signals
Let's say we want to load the todos based on a todoId
This will work fine, but one this to notice is that loader
untracked
todoId
Separate the request and the loader
We want our resource to refresh the data (call the loader again) every time the todoId
request
Now, when the todoId
What if we have previous unfinished requests? Let's say we want to cancel the previous request when the todoId
abortSignal
This will cancel the previous request when the todoId
We can also have multiple request dependencies, for example:
Now, the todosResource
limit
query
limit
query
loader
What happens when we have a request in progress and update data locally?
If that's the case, the resource API will automatically update the data locally, but cancel the ongoing request.
Create more reusable resources
By separating reactive values from the loader function, we can move the logic of the loader
Before:
After:
The todoLoader
ResourceLoaderParams
request
RxResource -> The Observable based resource API
Angular has always been about using Observables when it comes to data loading. This means, that we can use Observables to derive the data loading instead of using signals & promises.
In order to make this possible, we can use the rxResource
This will make the request based on the limit signal, and the loader
limit
And same as we can change local state with the signals, we can also change the local state with the observables implementation in the rxResource
Summary
We have 2 new primitives [resource, rxResource] that will help us make our life easier when dealing with data loading in Angular. These primitives have been requested for so long now, and will land in v19 as developer previews.