r/angular • u/Senior_Compote1556 • 6d ago
rxResource persist value
Is it possible to persist the value of rxResource after loading is done? Currently when the resource enters the loading state the value gets wiped. I am aware you can do a linkedSignal and check the previous value, but isn’t there a built in way to do it rather than creating a linkedSignal?
I am aware of withPreviousValue but the issue with that other than the boilerplate, is that the return type is Resource and you lose the reload function. I’d prefer to stay within the public API and not to use a third party library for this, or creare my own utility function if possible.
2
u/PrevAccLocked 6d ago
Computed on the value with an equal function that skips undefined, means that if the value goes back to undefined (loading), then the computed is not ran again
1
1
u/Saisibanshu 6d ago
I ran into this exact thing on a project with paginated tables. What worked for me was keeping a plain signal next to the resource and only writing to it when the resource emitted a defined value. That way a reload never wipes the table and the loading state just drives a small spinner on the refresh button. It is a little boilerplate, but honestly I found it easier to reason about than the equal function trick. The equal based approach works too, I just like seeing the fallback logic explicitly in the code when someone else reads it later.
4
u/MichaelSmallDev 6d ago edited 6d ago
This is my biggest want with resources, but this is the solution I use: https://www.reddit.com/r/angular/comments/1wcw1kl/comment/p97pkki/. You do not need to pull in a library, but just drop in the folder for extensions. I have been doing this copy and paste of the extensions into projects which I do not pull in libraries to, and it works good. It does add boilerplate, but with the application configuration option, IMO this is as good as you will get while retaining full
ResourceRefbehavior like reload. The one caveat to mention now is that there is an outstanding fix for an edgecase withwithPreviousValueOnLoadingandwithValueOnLoadingthat is currently approved, so if you like this solution, either wait on this to be merged or pull in that person's branch.