如何在 TypeScript/Angular 中点击可观察值来返回?

JCr*_*ew0 0 rest httprequest observable typescript angular

我正在尝试在服务中创建一种方法。该方法应该:

  • 对 REST API 进行 GET 调用
  • 更改参数的解决方案组件 (string[]) 以包含 get 调用的结果
  • 返回更改后的参数。

但是,我不希望它作为可观察对象返回,因为我正在更改它在组件中返回的对象。

现在我的方法如下所示:

private GET_URL = '...';
getSolutions(dog: Dog): Dog {
   let opts = new HttpParams();
   //set params
   this.http.get<Array<string>>(this.GET_URL, {params: opts}).pipe(
      tap(solutions => {
         dog.solutions = solutions;
         return dog
      }),
      catchError(//calls to an error handling method I made)
   )
   return dog
}
Run Code Online (Sandbox Code Playgroud)

我希望它进入水龙头,改变解决方案,然后返回水龙头。然而,它似乎击中了下面的返回值(它就在那里,所以有一个默认的返回值)。

有没有人有什么建议?

pet*_*ter 5

tap不允许您更改结果,您需要改为使用map。更多关于tapvs 的内容mapRxJS 中的 tap 和 map 有什么区别?

另外,我不确定您想dog立即返回,因为它会在执行调用和dog修改参数之前返回:

private GET_URL = '...';
getSolutions(dog: Dog): Dog {
   let opts = new HttpParams();
   //set params
   // changed to return stream
   return this.http.get<Array<string>>(this.GET_URL, {params: opts}).pipe(
      map(solutions => { // <- change to map
         dog.solutions = solutions;
         return dog
      }),
      catchError(//calls to an error handling method I made)
   )
   // return dog // this would return before the URL was executed
}
Run Code Online (Sandbox Code Playgroud)