Kildareflare
Kildareflare

Reputation: 4768

Combine two observables then transform the result

I have a REST endpoint that I am calling with Angular Http. I need to chain two calls, then use the results from each to create an object to return.

Pseudo code:

I thought this would do it, but I get an error;

addClient(clientData) {
   let clientUid;
   return this.http.post(`/clients`, clientData)
     .flatMap((newClient:any) => {
       clientUid = newClient.name;
       return this.http.patch(`/spec/${clientUid}`, clientData)
       .flatMap((updatedClient:any)=> {
         return {
           uid: clientUid,
           ...updatedClient,
        }
      })
   });
}
//consume
 this.clientService.addClient(clientData)
    .subscribe((response:any) =>{ }

TypeError: You provided an invalid object where a stream was expected. You can provide an Observable, Promise, Array, or Iterable.

How can I:

Upvotes: 2

Views: 460

Answers (2)

Jecfish
Jecfish

Reputation: 4189

There are some error + improvement can be done in your code.

  1. Improvement: you don't need to nested your flatmap call.
  2. Error: you don't need the second flatmap. What you need is map

I have created a demo for your problem - https://stackblitz.com/edit/so-rxjs.

Upvotes: 1

user184994
user184994

Reputation: 18281

The .flatMap function is expecting you to return an Observable, but you're actually returning an object.

If you want to transform the value, instead you should be using .map

Regarding using clientUuid, seeing as your map is being called from within the original flatMap, you should just be able to use newClient.name

Upvotes: 1

Related Questions