Created
October 9, 2019 07:20
-
-
Save mphuget/61c371d7d7a0dd5a00fa90434a8d370a to your computer and use it in GitHub Desktop.
rest.service.ts
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 { Observable, of, throwError } from 'rxjs'; | |
import { HttpClient, HttpHeaders, HttpErrorResponse } from '@angular/common/http'; | |
import { catchError, tap, map } from 'rxjs/operators'; | |
const httpOptions = { | |
headers: new HttpHeaders({'Content-Type': 'application/json'}) | |
}; | |
@Injectable({ | |
providedIn: 'root' | |
}) | |
export class RestService { | |
constructor(private http: HttpClient) { } | |
private handleError(error: HttpErrorResponse) { | |
if (error.error instanceof ErrorEvent) { | |
// A client-side or network error occurred. Handle it accordingly. | |
console.error('An error occurred:', error.error.message); | |
} else { | |
// The backend returned an unsuccessful response code. | |
// The response body may contain clues as to what went wrong, | |
console.error( | |
`Backend returned code ${error.status}, ` + | |
`body was: ${error.error}`); | |
} | |
// return an observable with a user-facing error message | |
return throwError('Something bad happened; please try again later.'); | |
} | |
private extractData(res: Response) { | |
let body = res; | |
return body || { }; | |
} | |
getTodos(): Observable<any> { | |
const apiUrl = "http://localhost:3000/api/todos"; | |
return this.http.get(apiUrl, httpOptions).pipe( | |
map(this.extractData), | |
catchError(this.handleError)); | |
} | |
getTodo(id:any): Observable<any> { | |
const apiUrl = "http://localhost:3000/api/todo/" + id; | |
return this.http.get(apiUrl, httpOptions).pipe( | |
map(this.extractData), | |
catchError(this.handleError)); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment