I have a dashboard with dynamic widgets adding up, If a user adds two widgets which have same api call, it obviously hit two ajax call. How can I make sure, if the API is called once, the second call get the result of first one
Asked
Active
Viewed 842 times
2
-
You can use `Promises` and sequentially execute them. Take a look at this SO question: https://stackoverflow.com/a/45649612/4091337 – Teun van der Wijst Nov 20 '18 at 11:58
-
You can check Observable. shareReplay operator. this might help. – Suresh Kumar Ariya Nov 20 '18 at 12:35
1 Answers
0
You can use the shareReplay
operator. It is caching the results and emits them to new subscribers without creating the stream again.
import { ajax } from 'rxjs/ajax';
import { tap, map, shareReplay } from 'rxjs/operators';
const endpoint = 'https://api.github.com/users?per_page=1'
const obs$ = ajax.getJSON(endpoint).pipe(
tap(() => console.log('Making BE call')),
shareReplay(1)
);
obs$.subscribe(x => console.log('[1]', x));
obs$.subscribe(x => console.log('[2]', x));
// Output:
// Making BE call
// [1] object
// [2] object
You can have a look at this small demo: https://stackblitz.com/edit/rxjs-eyk9y5

Bene
- 874
- 1
- 10
- 15