1

I have a HTTP get request that use a book name in url to find a price for the book. I added a loop to get all the prices of the books added to to array. But it seems like the next iterations don't go through. Books[0] works fine and price are added from the API.

When I try to log the iterations, it also stops after index 0.

books: {  name: String, price: String} [] = [
    { "name": "dash", "price": "N/A" }
    { "name": "tash", "price": "N/A" }
    { "name": "mash", "price": "N/A" }
];

getti() {
    var i: number;
    for (i = 0; i < this.books.length; i++) {
        console.log(i);
        return this.http.get(url+this.books[i].name)
            .map(res => {
                if (res)
                    this.books[i].price = res.json();
          });
    }
}
8
  • 1
    you should not be doing one http request per iteration. you should rather send your array to server, have server filter collection that meets criteria (array) and return all. that way you have just one http call and no loop. Commented Jul 30, 2017 at 10:28
  • 1
    You can only return once from a function, after that it's over and the rest of your loop never happens. Look into the RxJS methods e.g. concatAll to combine the results of multiple requests and return a single observable. Commented Jul 30, 2017 at 10:31
  • deezg, Okay, I don't have acces to server side. @jonrsharpe. Okay, thanks. I will have a look at RxJS methods, then. Commented Jul 30, 2017 at 10:34
  • the http request will be returned only once. why not use multiple streams of rsjs and the use concat method and return the results. i have not tried that but a simpler novoice way of doing it is- do a loop of all the requests and assign the results in an array and then when all of the iterations are done the return the final array of results Commented Jul 30, 2017 at 10:55
  • I watched videoes and read about rxjs after watching your comments. But I don't see how i could e.g implement the concatAll method. Is it possible for some of you guys to show me how its done with my example? Commented Jul 30, 2017 at 13:53

0

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.