结合两个可观察量然后转换结果

Combine two observables then transform the result

我有一个正在使用 Angular Http 调用的 REST 端点。 我需要链接两个调用,然后使用每个调用的结果为 return.

创建一个对象

伪代码:

我以为这样就可以了,但我收到一个错误;

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.

我怎样才能:

.flatMap 函数期望您 return 一个 Observable,但您实际上 return 是一个对象。

如果你想转换值,你应该使用 .map

关于使用 clientUuid,鉴于您的 map 是从原始 flatMap 中调用的,您应该只能使用 newClient.name

您的代码中存在一些错误 + 可以进行改进。

  1. 改进:您不需要嵌套 flatmap 调用。
  2. 错误:您不需要第二个 flatmap。你需要的是map

我已经为您的问题创建了一个演示 - https://stackblitz.com/edit/so-rxjs