0

Here's my code for a stacked http.get, which retrieves an object and then the object's details:

getDetails(sysID:string){

  console.log("entered getDetails");

  var details;
  this.http.get('https://blahURL').map(res => res.json()).subscribe(
   (data) => details = data,        // Reach here if res.status >= 200 && <= 299
   (err) => console.log(err),       // Reach here if fails
   ()==>{                           // On completion

     console.log("reached end of first get");

     this.http.get(...).map(res2 => res2.json()).subscribe(
        (data2) => {return data2;
        ...

This is called via console.log(getDetails(sysID));. So what I would expect is that when the second this.http.get() receives a result, it is passed to the caller and printed in the console. However, what I get in console is: entered getDetailsand then undefined, and only after that reached end of first get

How would I force it to wait for the second http.get results?

AndyZ
  • 3
  • 2

2 Answers2

1

you want wait a second request until return the response , so you should make ( chain two calls ) see ( How to chain Http calls in Angular2 ).

Bassam
  • 831
  • 8
  • 17
  • Thanks for this! I finally figured out that I cant use `subscribe` at any point in the http.get chain, otherwise it directly returns. When using only `map`and `flatmap` in the entire chain, it works just fine! – AndyZ Sep 10 '17 at 09:45
0

Apart from handling it with inside the completion event, you can also add skipWhile to prevent the subscription if the object is empty or undefined

this.http.get('https://blahURL').map(res => res.json())
   .skipWhile(data=> {if(data) return true;}) ///////////////////////
   .subscribe(
   (data) => details = data,        // Reach here if res.status >= 200 && <= 299
   (err) => console.log(err),       // Reach here if fails
   ()==>{                           // On completion

     console.log("reached end of first get");

     this.http.get(...).map(res2 => res2.json()).subscribe(
        (data2) => {return data2;
        ...

So in the first subscription, it will be skipped as per skipWhile. Second subscription it will have data and the corresponding flow will be as is

Aravind
  • 40,391
  • 16
  • 91
  • 110