Created
January 7, 2018 12:03
-
-
Save uno-de-piera/32e40b50666320c3a19510326a430b2f to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import { Injectable }from '@angular/core'; | |
import { HttpClient, HttpHeaders }from '@angular/common/http'; | |
import { Observable } from 'rxjs/Observable'; | |
import { catchError, tap } from 'rxjs/operators'; | |
import {User} from './user'; | |
import {of} from "rxjs/observable/of"; | |
const httpOptions = { headers: new HttpHeaders({ 'Content-Type': 'application/json' })}; | |
@Injectable() | |
export class UsersService { | |
private usersUrl: string = '/api/users'; | |
constructor (private http: HttpClient) {} | |
getUsers(): Observable<User[]> { | |
return this.http.get<User[]>(this.usersUrl) | |
.pipe( | |
tap(heroes => this.log(`fetched users`)), | |
catchError(this.handleError('getUsers', [])) | |
); | |
} | |
getUser(id: number): Observable<User> { | |
const url = `${this.usersUrl}/${id}`; | |
return this.http.get<User>(url).pipe( | |
tap(_ => this.log(`fetched hero id=${id}`)), | |
catchError(this.handleError<User>(`getUser id=${id}`)) | |
); | |
} | |
addUser (user: User): Observable<User> { | |
return this.http.post<User>(this.usersUrl, user, httpOptions).pipe( | |
tap((user: User) => this.log(`added User w/ id=${user.id}`)), | |
catchError(this.handleError<User>('addUser')) | |
); | |
} | |
deleteUser (id: string): Observable<User> { | |
const url = `${this.usersUrl}/${id}`; | |
return this.http.delete<User>(url, httpOptions).pipe( | |
tap(_ => this.log(`deleted user id=${id}`)), | |
catchError(this.handleError<User>('deleteUser')) | |
); | |
} | |
updateUser (user: User): Observable<null> { | |
return this.http.put(this.usersUrl, user, httpOptions).pipe( | |
tap(_ => this.log(`updated user id=${user.id}`)), | |
catchError(this.handleError<any>('updateUser')) | |
); | |
} | |
private handleError<T> (operation = 'operation', result?: T) { | |
return (error: any): Observable<T> => { | |
console.error(error); | |
return of(result as T); | |
}; | |
} | |
private log(message: string) { | |
console.log('UserService: ' + message); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment