0

Using Angular 5, I have created a function that gets data from a web request. Based on the data received from the request, I have a second web request firing based on the received System.Title. However, the function is firing the parts of the first loop and waiting to fire the second loop until the end of the first loop. How can I fix this?

Here is the TS:

selectedDocType(title){    
    this.http.get("https://test.com/items?$select=Title,Image,Source/Title,System/Title&$filter=Title eq '" + title + "'").subscribe(data => {

      for (let i = 0; i < data['value'].length; i++) {
          let system = data['value'][i].System.Title;

          // REVIEW: FIRING AT END OF MAIN LOOP
          this.http.get("https://test.com/items?$select=Title,Location,Image&$filter=Title eq '" + system + "'").subscribe(data => {

            for (let i = 0; i < data['value'].length; i++) {
                var systemlocation = data['value'][i].Location;
                this.location = data['value'][i].Location;
                console.log("this.location", this.location)  // REVIEW: LAST LOG IN CONSOLE; DEFINED CORRECTLY
            }
          });

        let sources = data['value'][i].Source;
        for (let i = 0; i < sources.length; i++) {
            console.log("this.location", this.location) // REVIEW: UNDEFINED    
        };
        console.log("at end of main loop") // REVIEW: FIRES BEFORE LAST LOG
      }
    });
}
cfoster5
  • 1,696
  • 5
  • 28
  • 42
  • Possible duplicate of [How do I return the response from an asynchronous call?](https://stackoverflow.com/questions/14220321/how-do-i-return-the-response-from-an-asynchronous-call) – gforce301 Apr 24 '18 at 18:43
  • 1
    anything that uses the data returned from the request (such as location) should be inside that requests callback function. – Andrew Lohr Apr 24 '18 at 18:45

0 Answers0