I'm trying to implement a cache in my angular/typescript project to prevent repeated http.get() calls to convert a userId into user full name.
dataService returns a list of object, for example object looks like this {location: 'abc', food: 'abc', userId: 'idA'}, for display, I want to transform each object to look like this: {location: 'abc', food: 'abc', userId: 'idA', fullName: 'John Doe'}
getEvents(param1){ const cache = new Map<string, string>(); this.dataService.getEvents(param1).subscribe( async res => { this.eventsData = []; for(let item of res.items){ const key: string = item.userId; if(cache.get(key)){ item.fullName = cache.get(key); } else{ await this.nameService.getFullName(key).subscribe( res=> { cache.set(key, res); item.fullName = res; } ) } this.eventsData.push(item); } } ); } The reason that I put Async,await is because I want each item to be processed sequentially, if second row of data has the same userId, it would do the lookup in the Map, instead of making a call to the nameService. And I have prior knowledge that for example out of 100 rows of data, it's only a few users.
for a list of size 3 has exactly the same userId, my code above somehow still makes 3 calls to NameService.
And I have tried taking the code block starting at for() to push(item) out to another function and put await in front of that function, that didn't reduce the number of calls to nameService(which in turn makes a http get call) either. What's the issue with my code? and if there is better ways to cache http get calls, please let me know.
I have tried the shareReplay answer in here:https://stackoverflow.com/questions/49797910/angular-5-caching-http-service-api-calls But it didn't seem to reduce the number of calls either. maybe I didn't get what the answer meant. Thank you.
...subscribe(...)returns aPromise?subscribeimplies it's anObservable, not a Promise, soawaitwon't do what you're expecting..toPromise()instead ofsubscribe(...). You can then useawait