Created
February 19, 2019 13:11
-
-
Save mphuget/e65a98dabf21b45c64f2554aaf922e09 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