使用调用 API 时处理错误

Handle errors when calling an API using

在 Angular 7 组件上,我正在调用服务:

this.postService.getByCategoryId(10)

    .subscribe((response: GetPostsByCategoryIdResponse>) => {

      this.posts = response.map((post: PostModel) => ({ 
        id: response.id, 
        title: response.title, 
        category: response.category.name
      }));

    });

我正在将模仿 API 返回的数据结构的 GetPostsByCategoryIdResponse 映射到组件中使用的 PostModel。

PostService 的 GetByCategoryId 正在调用 API:

  public GetByCategoryId(id: number): Observable<GetPostsByCategoryIdResponse> {

    return this.httpClient.get<GetPostsByCategoryIdResponse>(url);

  }

如何处理调用API时可能出现的错误?

To catch errors, you "pipe" the observable result from http.get() through an RxJS catchError() operator.

https://angular.io/tutorial/toh-pt6#error-handling

return this.httpClient.get<GetPostsByCategoryIdResponse>(url)
   .pipe(catchError((error) => {
          // some code
         return throwError("some error");
    })

此外,为了模仿 postModel 接受的数据,您可以使用 rxjs 的 map() 运算符修改 Observable,而不是修改 subscribe() 中的结果。

return this.httpClient.get<GetPostsByCategoryIdResponse>(url)
   .pipe(
        map(data) => {
           // your mapping
           return mappedData
        },
        catchError((error) => {
              // some code
             return throwError("some error");
        })