Search code examples
javascriptangularrxjs

How should i handle error and response before forwarding it to subscriber in rxjs lastValueFrom with pipe(take(1))


Here is my code -

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

How should i implement 'catch' block in this or 'handle response' before forwarding it to subscriber?


Solution

  • Firstly, to answer your question, I would like to point out that you don't have to choose, yoou can very well handle the error twice, once in your service as well as inside your component.

    You could for example delegate some "global" logic to the Service like pushing an error notification, throw the error again and then catch it to handle business logic inside your consumer component.

    Consider this small example, we use the catchError RxJS operator to catch the error, do logic and then throw it again for the App component to handle it.

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

    I'd like to point out a few things that I changed, for example the take(1) isn't necessary in this context as the HttpClient will always emit always only one value before completing.

    I've also used the HttpParams option to pass the query param to the HttpClient instead of including it directly in the request uri.

    I'd also like to say that I wouldn't recommand such an explicit use of any and I encourage you to try and type your http requests, this could save you some headache.