-
Notifications
You must be signed in to change notification settings - Fork 36
Expand file tree
/
Copy pathrest.service.ts
More file actions
71 lines (58 loc) · 2.12 KB
/
rest.service.ts
File metadata and controls
71 lines (58 loc) · 2.12 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
import { Injectable } from '@angular/core';
import { HttpClient, HttpHeaders, HttpErrorResponse } from '@angular/common/http';
import { Observable, of } from 'rxjs';
import { map, catchError, tap } from 'rxjs/operators';
const endpoint = 'http://localhost:3000/api/v1/';
const httpOptions = {
headers: new HttpHeaders({
'Content-Type': 'application/json'
})
};
@Injectable({
providedIn: 'root'
})
export class RestService {
constructor(private http: HttpClient) {}
private extractData(res: Response) {
const body = res;
return body || { };
}
getProducts(): Observable<any> {
return this.http.get(endpoint + 'products').pipe(
map(this.extractData));
}
getProduct(id): Observable<any> {
return this.http.get(endpoint + 'products/' + id).pipe(
map(this.extractData));
}
addProduct (product): Observable<any> {
console.log(product);
return this.http.post<any>(endpoint + 'products', JSON.stringify(product), httpOptions).pipe(
// tslint:disable-next-line:no-shadowed-variable
tap((product) => console.log(`added product w/ id=${product.id}`)),
catchError(this.handleError<any>('addProduct'))
);
}
updateProduct (id, product): Observable<any> {
return this.http.put(endpoint + 'products/' + id, JSON.stringify(product), httpOptions).pipe(
tap(_ => console.log(`updated product id=${id}`)),
catchError(this.handleError<any>('updateProduct'))
);
}
deleteProduct (id): Observable<any> {
return this.http.delete<any>(endpoint + 'products/' + id, httpOptions).pipe(
tap(_ => console.log(`deleted product id=${id}`)),
catchError(this.handleError<any>('deleteProduct'))
);
}
private handleError<T> (operation = 'operation', result?: T) {
return (error: any): Observable<T> => {
// TODO: send the error to remote logging infrastructure
console.error(error); // log to console instead
// TODO: better job of transforming error for user consumption
console.log(`${operation} failed: ${error.message}`);
// Let the app keep running by returning an empty result.
return of(result as T);
};
}
}