0

Having difficulty wrapping my head around observables. I have the following:

const check = this.http.get(myUrl);

This returns JSON data. I want to test that the "url" field exists in the JSON data. If it doesn't I'd like to query a second URL. (Assume the API is fixed and two calls are necessary, because that is in fact the case.)

The problem is that I can't figure out how to do that. If check was just JSON (and no an observable) this would be trivial:

if(check.url) {
    return check;
} else {
    return this.http.get(myOtherUrl);
}

This clearly doesn't work as I can't directly check the URL property. Reading the page on RxJS operators, I've written the following:

const check = this.http.get(myUrl);
const mapResponse = map(response => {
    ...format data into JSON structure...
    return jsonResponse;
});
mapResponse(check).subscribe(result => {
  if (result['url']) {
      return result;
  } else {
      return this.http.get(myOtherUrl);
  }
});

This looks crazy awkward, as in order to use the second get I'd have to replicate the code within the lambda function. Not sure how to access the result of the second http call to actually do something with it. Should I just nest the entire thing again?

marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
eykanal
  • 26,437
  • 19
  • 82
  • 113
  • As I was posting I noticed [this](https://stackoverflow.com/q/49926634/168775), but wasn't sure if that was the answer I'm looking for here. – eykanal Nov 04 '20 at 21:04
  • What do you think returning a value from a subscribe callback do? – Ruan Mendes Nov 04 '20 at 21:06
  • I apologize, the return shouldn't be there. Edited. – eykanal Nov 04 '20 at 21:08
  • You need to subscribe to the `this.http.get(myOtherUrl)` observable, yes nested inside, I'm not sure why you don't want to do that – Ruan Mendes Nov 04 '20 at 21:14
  • You need to chain your calls, I don't know the exact syntax but something along the lines of `this.http.get(myUrl).pipe(flatMap(response) => response.url ? response : this.http.get(myOtherUrl);)` That should return an observable for the first or second request depending on whether the first call had a `url` property. See https://stackoverflow.com/questions/34104638/how-to-chain-http-calls-in-angular2 – Ruan Mendes Nov 04 '20 at 21:27
  • Also consider [converting the observables to Promises](https://stackoverflow.com/a/52497250/227299), it would make it more readable if you're not an rx-js expert. – Ruan Mendes Nov 04 '20 at 21:48

0 Answers0