在将错误和响应转发给 rxjs lastValueFrom 中的订阅者之前,我应该如何处理错误和响应(take(1))

问题描述 投票:0回答:1

这是我的代码-

async getItemById(idParam: string): Promise<any>  {
    return await lastValueFrom<any>(this.http.get('http://localhost:3000/api/item?id=' + idParam).pipe(take(1)))
}

在将其转发给订阅者之前,我应该如何在此或“处理响应”中实现“捕获”块?

javascript angular rxjs
1个回答
0
投票

首先,为了回答你的问题,我想指出你不必选择,你可以很好地处理错误两次,一次在你的服务中,一次在你的组件内部。

例如,您可以将一些“全局”逻辑委托给服务,例如推送错误通知,再次抛出错误,然后捕获它以处理消费者组件内的业务逻辑。

考虑这个小例子,我们使用 catchError RxJS 运算符来捕获错误,执行逻辑,然后再次抛出错误以供 App 组件处理。

export class HttpService {

  private http = inject(HttpClient)

  async getItemById(idParam: string): Promise<any>  {
    return await lastValueFrom<any>(this.http.get('http://localhost:3000/api/item', {params: {id: idParam}}).pipe(
      catchError(error => {
        // Do something like pushing a notification to signal the error to the user
        return throwError(() => new Error("Error during request"))
      })
    ));
  }
}

export class App implements OnInit {

  private httpService = inject(HttpService);
  
  ngOnInit() {
    this.httpService.getItemById('10')
    .then(console.log)
    .catch((error) => {
      // Handle business logic related to the error here 
    })
  }
}

我想指出我更改的一些内容,例如,在这种情况下

take(1)
不是必需的,因为
HttpClient
在完成之前始终只发出一个值。

我还使用了

HttpParams
选项将查询参数传递给
HttpClient
,而不是直接将其包含在请求 uri 中。

我还想说,我不会建议如此明确地使用

any
,我鼓励你尝试输入你的 http 请求,这可以让你省去一些麻烦。

© www.soinside.com 2019 - 2024. All rights reserved.