【问题标题】:Handle errors when calling an API using使用调用 API 时处理错误
【发布时间】:2019-01-07 20:43:27
【问题描述】:

在 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时可能出现的错误?

【问题讨论】:

    标签: angular angular6 angular7 angular-httpclient


    【解决方案1】:

    要捕获错误,您可以通过 RxJS 的 catchError() 运算符“管道”来自 http.get() 的可观察结果。

    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");
            })
    

    【讨论】:

    • subscribe中修改结果有问题吗?我这样做是因为 GetByCategoryId 服务方法被不同的组件调用,并且每个组件都有自己的模型,所以我无法在服务方法上进行映射,因为那时我不知道应该映射到哪里它到。
    • @MiguelMoura 不,修改订阅中的数据没有问题,这完全取决于您的要求。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-10-24
    • 2023-01-16
    • 2017-07-29
    • 1970-01-01
    • 1970-01-01
    • 2018-11-05
    • 2019-10-04
    相关资源
    最近更新 更多