Skip to content

Instantly share code, notes, and snippets.

@mphuget
Created February 19, 2019 13:11
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mphuget/e65a98dabf21b45c64f2554aaf922e09 to your computer and use it in GitHub Desktop.
Save mphuget/e65a98dabf21b45c64f2554aaf922e09 to your computer and use it in GitHub Desktop.
Rest-service.ts
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