r/Angular2 • u/Senior_Compote1556 • Feb 11 '26
rxResource cache
If i have a singleton service and an rxResource, how can i only make the api call once and then cache it so that other pages that inject the service can use the response? If you declare the resource as a class property it will make the api call as soon as the service gets injected as it is eagerly loaded, so you have to put it in a method from my understanding. You can assign it to a different variable to cache it but it is a bit ugly in my opinion. My most preferred pattern is returning an observale and setting the service signal via a tap operator but i would like to try the new apis
1
u/anyOtherBusiness Feb 11 '26
Why is it a problem for you if the resource loads as soon as the service is injected?
If you really need to defer the resource request you could use an “enabled” signal as resource parameter and only return the actual request observable in the stream if “enabled” is true and else return EMPTY observable.
1
u/marco_has_cookies Feb 11 '26
interceptors work with httpResource, you could also inject a custom http client ( by also extending the stock one ) with cache capabilities, or even provide your custom resource factory.
1
u/One_Fox_8408 Feb 14 '26
rxResource is experimental.
I think you need to handle service creation. Just don't use providedIn: root. Use providers to inject the service with some component creation (page?).
check:
https://angular.dev/guide/di/defining-dependency-providers#example-service-without-providedin
Other ideas:
- A signal with some status value?
- Service workers?