0

I'm currently working on executing multiple HTTP get requests after each other(chaining), on my component, 'onInit'. I basically want to get ids(string), map them to a local array, for each element of this array perform a HTTP get request(id), map these result to a local array, get the ids... etc.

So as you can tell alot of repeated requests after each other where each request depends on the result of the previous one.

// Get the dataassociations from the distinct ids
for (const dataASSID of distinctDataAssIDs) {
  this.api.getDataAssociationByID(dataASSID).subscribe(
    data => {
    this.DataAssociations.push(data.body.entities.DATAASSOCIATIONS[0]);
  });
}

// Get dataobject ids from dataassociations
const dataobjIDs: string[] = new Array();
for (const dataAss of this.DataAssociations) {
  console.log(dataAss.languages.DUT + 'rsultrtrt');
  if (dataAss.DATAOBJECTS !== undefined) {
  for (const id of dataAss.DATAOBJECTS) {
    dataobjIDs.push(id);
  }
}
}
console.log(dataobjIDs);

// make ids distinct
let distinctDataObjIDs = new Array();
distinctDataObjIDs = Array.from(new Set(dataobjIDs));

console.log(distinctDataObjIDs);

// Get the dataobjects from the distinct ids
for (const dataObjID of distinctDataObjIDs) {
  this.api.getDataObjectByID(dataObjID).subscribe(data => {
    this.DataObjects.push(data.body.entities.DATAOBJECTS[0]);
  });
}

Iknow that it is currently spaghetti code, however my question is how can i chain these request? because after the subscribe() of the first get request. The next get cant be executed because the response is not yet received during the execution of code.

UPDATE 1 (based on duplicate) I wish it was, but my request are all surounded with for loops which makes my situation difficult. Because i want to execute a request for each id i get from the previous request

6
  • 1
    Possible duplicate of Angular 2 - Chaining http requests Commented Nov 7, 2017 at 13:37
  • I wish it was, but my request are all surounded with for loops which makes my situation difficult. Because i want to execute a request for each id i get from the previous request. And I also want to save the result of the request locally in an array Commented Nov 7, 2017 at 13:59
  • If you add the interfaces returned by your service and the definitions of your service methods, it would be easier to help Commented Nov 7, 2017 at 14:39
  • Thank you for the feedback you are right this question is unclear, I was a bit salty when I was struggling with this issue sorry. I have created a new question for this problem with the use of promises stackoverflow.com/questions/47176007/… Commented Nov 8, 2017 at 9:36
  • promises wont do the problem easier, and you still didnt added what I asked to the new question Commented Nov 8, 2017 at 11:05

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.