angular-tour-of-heroes/src/app/hero.service.ts
2022-09-30 11:30:08 +02:00

82 lines
2.4 KiB
TypeScript

import { HttpClient, HttpHeaders } from '@angular/common/http';
import { Injectable } from '@angular/core';
import { catchError, Observable, of, pipe, tap } from 'rxjs';
import { Hero } from './hero';
import { MessageService } from './messages.service';
import { HEROES } from './mock-heroes';
@Injectable({
providedIn: 'root'
})
export class HeroService {
httpOptions = {
headers: new HttpHeaders({ 'Content-Type': 'application/json' })
};
private heroesUrl = 'api/heroes'
constructor(private messageService: MessageService, private http: HttpClient) { }
getHeroes(): Observable<Hero[]> {
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}`
return this.http.get<Hero>(url).pipe(
tap(_ => this.log(`fetched hero id=${id}`)),
catchError(this.handleError<Hero>(`getHero id=${id}`))
)
}
updateHero(hero: Hero): Observable<any> {
return this.http.put(this.heroesUrl, hero, this.httpOptions).pipe(
tap(_ => this.log(`updated hero id=${hero.id}`)),
catchError(this.handleError<any>(`updatedHero`))
)
}
addHero(hero: Hero): Observable<Hero> {
return this.http.post<Hero>(this.heroesUrl, hero, this.httpOptions).pipe(
tap((newHero: Hero) => this.log(`added hero w/ id=${newHero.id}`)),
catchError(this.handleError<Hero>('addHero'))
)
}
deleteHero(id: number): Observable<Hero> {
const url = `${this.heroesUrl}/${id}`
return this.http.delete<Hero>(url, this.httpOptions).pipe(
tap(_ => this.log(`deleted hero id=${id}`)),
catchError(this.handleError<Hero>('deleteHero'))
)
}
searchHeroes(term: string): Observable<Hero[]> {
if (!term.trim()) {
return of([])
}
return this.http.get<Hero[]>(`${this.heroesUrl}/?name=${term}`).pipe(
tap(x => x.length ?
this.log(`found heroes matching "${term}"`) :
this.log(`no heroes matching "${term}"`)),
catchError(this.handleError<Hero[]>('searchHeroes', []))
)
}
private log(message: string) {
this.messageService.add(`HeroService: ${message}`)
}
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)
}
}
}