2

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:

  • POST new entity to server and get a UID back
  • PATCH entity content to server, using UID returned
  • create an object that combines entity content and UID
  • return object to caller (subscribe)

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:

  • fix the error and have addClient return my desired object?
  • Also, is there a way I can consume the UID in the final flatMap without having to set the local variable (clientUid )?
Kildareflare
  • 4,590
  • 5
  • 51
  • 65
  • 1
    `flatMap` is expected you to return an Observable. but you're returning an object. Instead, you should use `.map` for that bit – user184994 Aug 19 '18 at 13:57
  • Doh! I actually started with map there, but changed to fix another issue. Changing it back does indeed work. Thanks. – Kildareflare Aug 19 '18 at 14:09
  • @user184994 if you add an answer I'll mark it as accepted. If you have any ideas on point 2, that would be most helpful too. – Kildareflare Aug 19 '18 at 14:10

2 Answers2

1

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

user184994
  • 17,791
  • 1
  • 46
  • 52
1

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.

Jecfish
  • 4,026
  • 1
  • 18
  • 16