I am loading JSON with a service using HTTP GET and use the passed observable with async pipe to display data in my template. An issue with this method is that the HTTP GET is executed and the JSON is downloaded each time I reference the observable in the template - I can verify this using my browser's DevTool/Network window.
Example service logic:
foo$ :Observable<T> = this.myFunction();
myFunction() {
return this.http.get<T>('...').pipe(...);
}
Example component logic:
constructor(public myService :MyService) { }
settings$ :Observable<T> = this.myService.foo$;
Example component template:
<input type="text" name="foo" value="{{(this.bar$ | async)?.foo}}"/>
I think a good workaround would be to create a similar service, which receives the observable from the initial service using HTTP GET and passes the new observable into the templates instead - this way, the HTTP GET itself would be executed once and the additional service would serve data to the template each time it is referenced.
Considering the structure of Angular I wonder if this is the right solution considering logic, readability and efficiency. Could someone verify this or provide a better solution please?
shareReplayoperator. This will allow you to share the result of the http call among multiple subscribers.