I have a button user can click on that makes an http call to fetch data.
When user click the button the first time, I make http call. If the user clicks the button again, just provide the data that was fetched earlier.
How do I do that without storing it in a local variable explicitly? I have tried few things but none seem to work. It always makes the http request. I have tried to use "shareReplay" and "share" operators.
<button (click)=getData()>Click me</button>
getData() {
source$.pipe(
switchMap(sourceVal => {
const source2$ = this.getSource2();
const source3$ = this.getSource3(); -------- I do not want this call to be made on subsequent button clicks because it's a reference data
return combineLatest([source2$, source3$])
}),
map(([source2Val, source3Val]) => {
//do some processing
return 'done'
})
)
}
I am using angular and rxjs.
you can disable the button or prevent sending multiple requests via a variable.
fetching = false;
getData() {
if(!this.fetching) {
this.fetching = true;
this.http.get('url').pipe(shareReplay(1), finalize(() => {
this.fetching = false;
}));
}
}