Skip to content

Commit

Permalink
v0.17.0: Tratamento de erro
Browse files Browse the repository at this point in the history
  • Loading branch information
peimelo committed Jul 4, 2020
1 parent 2dac951 commit 0a442a9
Showing 1 changed file with 20 additions and 5 deletions.
25 changes: 20 additions & 5 deletions src/app/hero.service.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
import { HttpClient } from '@angular/common/http';
import { Injectable } from '@angular/core';
import { Observable } from 'rxjs';
import { Observable, of } from 'rxjs';
import { catchError, tap } from 'rxjs/operators';
import { environment } from '../environments/environment';
import { Hero } from './hero.model';
import { MessageService } from './message.service';
Expand All @@ -17,15 +18,29 @@ export class HeroService {
) {}

getHeroes(): Observable<Hero[]> {
this.log('fetched heroes');
return this.http.get<Hero[]>(this.heroesUrl);
return this.http.get<Hero[]>(this.heroesUrl).pipe(
tap(() => this.log('fetched heroes')),
catchError(this.handleError<Hero[]>('getHeroes', []))
);
}

getHero(id: number): Observable<Hero> {
const url = `${this.heroesUrl}/${id}`;

this.log(`fetched hero id=${id}`);
return this.http.get<Hero>(url);
return this.http.get<Hero>(url).pipe(
tap(() => this.log(`fetched hero id=${id}`)),
catchError(this.handleError<Hero>('getHeroes'))
);
}

private handleError<T>(operation = 'operation', result?: T) {
return (error: any): Observable<T> => {
console.log(error);

this.log(`${operation} failed: ${error.message}`);

return of(result as T);
};
}

private log(message: string) {
Expand Down

0 comments on commit 0a442a9

Please sign in to comment.