0

I am really struggling with this problem :

I have a string[], let's call it keys

I have to loop for each value of keys and subscribe to a service to get a list of objects. What I want, is a Map<string, object[]>, so in this Map, each key is linked to a list of objects. Also, I need to sort object[] by name, so I tried this :

    let map =  new Map();
    keys.forEach(key => {
       this.getObjects(key).subscribe(objects => {
          map.set(key, objects.sort((a, b) => a.name - b.name));
       })
    });
    return map;

But it does not work properly, as soon as there is a delay in getObjects, my component does not get the complete Map. Do you have any proper solution ?

1
  • Not completely sure about the problem. I see that you return from the method before the map is fully populated. Is that the problem, do you want to 'wait' until you have a response from all subscriptions? Also 'subscribe' means (by the word/pattern) that you could expect more message as long as you're 'subscribed' to the service, it's not just fetching one? May 25, 2020 at 13:44

1 Answer 1

0

don't subscribe to multiple... use a higher order operator like forkJoin...

// forkjoin subscribes to all the observables you feed to it
return forkJoin(...keys.map(k => this.getObjects(k))).pipe(
  map(objects => { // this is all of the returned objects
    let mapUsages =  new Map();
    // do whatever in here, your code is unclear on what's happening here.
    objects.forEach(object => mapUsages.set(natureEmplacement.code, usages.sort((a, b) => a.name - b.name)))
    return mapUsages; // return your final value
  })
)

then the function caller subscribes to the returned observable which will emit the complete map. Subscribe is asynchronous, so you can't return the map synchronously while awaiting the asynchronous values to populate it. You have to populate and return it in an async fashion.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.