1

Here's what I intend to do.

  • Request https://reqres.in/api/users/2
  • Which sends a response as follows.

    {
      "data": {
        "id": 2,
        "first_name": "Janet",
        "last_name": "Weaver",
        "avatar":
          "https://s3.amazonaws.com/uifaces/faces/twitter/josephstein/128.jpg"
      }
    }
    
    • Now, I wanna grab the avatar url and make another request, which gives me the image binary.

    • At the end of this, what I want as output is an Observable that gives me this data.

      {
        "data": {
          "id": 2,
          "first_name": "Janet",
          "last_name": "Weaver",
          "avatar":
            "BINARY_GIBBERISH HERE"
        }
      }
      

Here's how I approached but can't finish it.

this.http
  .get('https://reqres.in/api/users/2')
  .switchMap(a => {
    const image$ = this.http.get(a.json().data.avatar);
    const data = Observable.of(a.json().data);
    // Do something here to combine.
  })
  .subscribe(a => {
    // get data here.
  });
}

Basically, is there any way to have a structure like this,

{
  "data": {
    "id": 2,
    "first_name": "Janet",
    "last_name": "Weaver",
    "avatar": [Observable from this.http.get]
  }
}

Which then gets resolved to my final data?

1 Answer 1

2

You don't need to use switchMap for this and use concatMap or mergeMap instead:

this.http
  .get('https://reqres.in/api/users/2')
  .concatMap(a => {
    const data = a.json().data;
    const image$ = this.http.get(data.avatar);

    return image$.map(imageData => {
      data.avatar = imageData;
      return data;
    });
  })
  .subscribe(a => {
    // get data here.
  });
}
Sign up to request clarification or add additional context in comments.

1 Comment

Brilliant! Thanks so much :)

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.