0

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.

2
  • Are you sure that ...subscribe(...) returns a Promise? subscribe implies it's an Observable, not a Promise, so await won't do what you're expecting. Commented Sep 6, 2018 at 23:58
  • 1
    @Jacob: You should be able to do .toPromise() instead of subscribe(...). You can then use await Commented Sep 7, 2018 at 0:00

0

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.