From 033b12ef11385cfc341ac92a8cce6d0029688143 Mon Sep 17 00:00:00 2001 From: "DESKTOP-P9VU163\\admin" Date: Tue, 24 Jun 2025 09:21:53 +0300 Subject: [PATCH] add less 6 handleError --- src/app/hero.service.ts | 36 ++++++++++++++++++++++++++++-------- 1 file changed, 28 insertions(+), 8 deletions(-) diff --git a/src/app/hero.service.ts b/src/app/hero.service.ts index a419ff4..5462f55 100644 --- a/src/app/hero.service.ts +++ b/src/app/hero.service.ts @@ -4,6 +4,7 @@ import { HEROES } from './mock-heroes'; import { Observable, of } from 'rxjs'; import { MessageService } from './message.service'; import { HttpClient } from '@angular/common/http'; +import { catchError, map, tap } from 'rxjs/operators'; @Injectable({ providedIn: 'root' @@ -18,15 +19,11 @@ export class HeroService { private messageService: MessageService) { } - // getHeroes(): Observable { - // const heroes = of(HEROES); - // this.messageService.add('HeroService: fetched heroes'); - // return heroes; - // } - - /** GET heroes from the server */ getHeroes(): Observable { - return this.http.get(this.heroesUrl) + return this.http.get(this.heroesUrl) + .pipe( + catchError(this.handleError('getHeroes', [])) + ); } getHero(id: number): Observable { @@ -37,8 +34,31 @@ export class HeroService { return of(hero); } + /** + * Handle Http operation that failed. + * Let the app continue. + * + * @param operation - name of the operation that failed + * @param result - optional value to return as the observable result + */ + private handleError(operation = 'operation', result?: T) { + return (error: any): Observable => { + + // TODO: send the error to remote logging infrastructure + console.error(error); // log to console instead + + // TODO: better job of transforming error for user consumption + this.log(`${operation} failed: ${error.message}`); + + // Let the app keep running by returning an empty result. + return of(result as T); + }; + } + /** Log a HeroService message with the MessageService */ private log(message: string) { this.messageService.add(`HeroService: ${message}`); } + + } \ No newline at end of file