【问题标题】:How do I return in a tap on an observable in TypeScript/Angular?如何点击 TypeScript/Angular 中的 observable 返回?
【发布时间】:2021-09-09 04:08:32
【问题描述】:

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

  • 对 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
}

我希望它进入水龙头,改变解决方案,然后返回水龙头。然而,它似乎击中了下方的回报(那里只是为了有一个默认回报)。

有人有什么建议吗?

【问题讨论】:

    标签: angular typescript rest observable httprequest


    【解决方案1】:

    设置这样的服务方法

    getSolutions(dog: Dog): Observable<Dog> {
        return this.http.get<Dog>(this.GET_URL, {params: opts})
        .pipe(catchError(this.errorHandlerService.handleError));;
    }
    

    在这里处理错误

    @Injectable({
      providedIn: 'root'
    })
    export class ErrorHandlerService {
      constructor() { }
    
      public handleError(error: HttpErrorResponse) {
        if (error.error instanceof ErrorEvent) {
          // A client-side or network error occurred. Handle it accordingly.
          console.error('An error occurred:', error.error.message);
        } else {
          // The backend returned an unsuccessful response code.
          // The response body may contain clues as to what went wrong,
          console.error(
            `Backend returned code ${error.status}, ` + `body was: ${error.error}`
          );
        }
        // return an observable with a user-facing error message
        return throwError('Something bad happened; please try again later.');
      }
    
      // delay
      public delay(ms: number) {
        return new Promise(resolve => setTimeout(resolve, ms));
      }
    }
    

    然后在你的控制器中,你会得到这样的数据

        this.myService.getSolutions().subscribe((myDog : Dog) => {
          console.log(myDog);
        });
    

    【讨论】:

      【解决方案2】:

      tap 不允许您更改结果,您需要改用map。更多关于 tap 与 map: What is the difference between tap and map in RxJS?

      另外,我不确定您是否要立即返回 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
      }
      

      【讨论】:

        猜你喜欢
        • 2019-02-17
        • 1970-01-01
        • 2021-09-24
        • 1970-01-01
        • 2018-07-14
        • 1970-01-01
        • 1970-01-01
        • 2019-06-25
        • 1970-01-01
        相关资源
        最近更新 更多