Advertisement
Guest User

todo service

a guest
Dec 19th, 2018
144
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.25 KB | None | 0 0
  1. import {Injectable} from '@angular/core';
  2. import {HttpClient, HttpHeaders} from '@angular/common/http';
  3. import {Observable, of} from 'rxjs';
  4. import {map, catchError, tap} from 'rxjs/operators';
  5.  
  6. @Injectable({providedIn: 'root'})
  7. export class TodoService {
  8. public API = 'http://localhost:8080/';
  9.  
  10. httpOptions = {
  11. headers: new HttpHeaders({
  12. 'Content-Type': 'application/json'
  13. })
  14. };
  15.  
  16.  
  17. constructor(private http: HttpClient) {
  18. }
  19.  
  20. private extractData(res: Response) {
  21. const body = res;
  22. return body || {};
  23. }
  24.  
  25. // SPRING TUT
  26.  
  27. getToDos(): Observable<any> {
  28. return this.http.get(this.API + 'todos').pipe(
  29. map(this.extractData));
  30. }
  31.  
  32. getToDo(id): Observable<any> {
  33. return this.http.get(this.API + 'todos/' + id).pipe(
  34. map(this.extractData));
  35. }
  36.  
  37. addToDo(todo): Observable<any> {
  38. console.log(todo);
  39. return this.http.post<any>(this.API + 'todos', JSON.stringify(todo), this.httpOptions).pipe(
  40. tap((todo) => console.log(`added todo w/ id=${todo.id}`)),
  41. catchError(this.handleError<any>('addTodo'))
  42. );
  43. }
  44.  
  45. updateToDo(id, todo): Observable<any> {
  46. return this.http.put(this.API + 'todos/' + id, JSON.stringify(todo), this.httpOptions).pipe(
  47. tap(_ => console.log(`updated todo id=${id}`)),
  48. catchError(this.handleError<any>('updateTodo'))
  49. );
  50. }
  51.  
  52. deleteToDo(id): Observable<any> {
  53. return this.http.delete<any>(this.API + 'todos/' + id, this.httpOptions).pipe(
  54. tap(_ => console.log(`deleted todo id=${id}`)),
  55. catchError(this.handleError<any>('deleteToDo'))
  56. );
  57. }
  58.  
  59. private handleError<T>(operation = 'operation', result?: T) {
  60. return (error: any): Observable<T> => {
  61. // TODO: send the error to remote logging infrastructure
  62. console.error(error); // log to console instead
  63. // TODO: better job of transforming error for user consumption
  64. console.log(`${operation} failed: ${error.message}`);
  65. // Let the app keep running by returning an empty result.
  66. return of(result as T);
  67. };
  68. }
  69. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement