-1

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?

Miguel Moura
  • 36,732
  • 85
  • 259
  • 481

1 Answers1

1

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");
        })
Ashish Ranjan
  • 12,760
  • 5
  • 27
  • 51
  • Is there any problem in modifying the result in subscribe? I am doing this because GetByCategoryId service method is being called by different components and each one has its own model so I would not be able to do that mapping on the service method as I would not know, at that point, to where should I map it to. – Miguel Moura Jan 07 '19 at 12:47
  • @MiguelMoura No, there is no problem in modifying the data in subscribe, It completely depends on your requirement. – Ashish Ranjan Jan 07 '19 at 12:49