Search code examples
angularangular6angular7angular-httpclient

Handle errors when calling an API using


On an Angular 7 component I am calling a service:

this.postService.getByCategoryId(10)

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

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

    });

I am mapping the GetPostsByCategoryIdResponse, which mimics the data structure returned by the API, to a PostModel which is used in the component.

The PostService's GetByCategoryId is calling an API:

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

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

  }

How to handle errors that might occurred when calling the API?


Solution

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

    Also, to mimic the data as accepted by the postModel, you can use rxjs's map() operator to modify the Observable instead of modifying the result in subscribe().

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