2019-10-25 13:36:01 +00:00
|
|
|
import { Injectable } from '@angular/core';
|
|
|
|
import { Hero } from './hero';
|
|
|
|
import { Observable, of } from 'rxjs';
|
2019-10-25 13:56:29 +00:00
|
|
|
import { MessageService } from './message.service';
|
2019-10-25 18:26:04 +00:00
|
|
|
import { HttpClient, HttpHeaders } from '@angular/common/http';
|
|
|
|
import { catchError, map, tap } from 'rxjs/operators';
|
2019-10-25 13:36:01 +00:00
|
|
|
|
|
|
|
@Injectable({
|
|
|
|
providedIn: 'root'
|
|
|
|
})
|
|
|
|
export class HeroService {
|
|
|
|
|
2019-10-25 18:26:04 +00:00
|
|
|
constructor(
|
|
|
|
private http: HttpClient,
|
|
|
|
private messageService: MessageService) { }
|
|
|
|
|
|
|
|
private log(message: string) {
|
|
|
|
this.messageService.add(`HeroService: ${message}`)
|
|
|
|
}
|
|
|
|
|
|
|
|
private heroesUrl = 'api/heroes'; // URL to web api
|
2019-10-25 13:36:01 +00:00
|
|
|
|
|
|
|
getHeroes(): Observable<Hero[]> {
|
2019-10-25 18:26:04 +00:00
|
|
|
return this.http.get<Hero[]>(this.heroesUrl)
|
|
|
|
.pipe(
|
|
|
|
catchError(this.handleError<Hero[]>('getHeroes', []))
|
|
|
|
);
|
2019-10-25 13:36:01 +00:00
|
|
|
}
|
2019-10-25 15:39:24 +00:00
|
|
|
|
2019-10-25 18:26:04 +00:00
|
|
|
/** GET hero by id. Will 404 if id not found */
|
2019-10-25 15:39:24 +00:00
|
|
|
getHero(id: number): Observable<Hero> {
|
2019-10-25 18:26:04 +00:00
|
|
|
const url = `${this.heroesUrl}/${id}`;
|
|
|
|
return this.http.get<Hero>(url).pipe(
|
|
|
|
tap(_ => this.log(`fetched hero id=${id}`)),
|
|
|
|
catchError(this.handleError<Hero>(`getHero id=${id}`))
|
|
|
|
);
|
|
|
|
}
|
|
|
|
|
|
|
|
/**
|
|
|
|
* 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<T> (operation = 'operation', result?: T) {
|
|
|
|
return (error: any): Observable<T> => {
|
|
|
|
|
|
|
|
// 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);
|
|
|
|
};
|
2019-10-25 15:39:24 +00:00
|
|
|
}
|
2019-10-25 13:36:01 +00:00
|
|
|
}
|