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 ) { } private extractData ( res ) { let body = res ; return body || { } ; } getProducts ( ) { return this . http . get ( endpoint + 'products' ) . pipe ( map ( this . extractData ) ) ; } getProduct ( id ) { return this . http . get ( endpoint + 'products/' + id ) . pipe ( map ( this . extractData ) ) ; } addProduct ( product ) { console . log ( product ) ; return this . http . post < any > ( endpoint + 'products' , JSON . stringify ( product ) , httpOptions ) . pipe ( tap ( ( product ) => console . log ( `added product w/ id=${ product . id }` ) ) , catchError ( this . handleError < any > ( 'addProduct' ) ) ) ; } updateProduct ( id , product ) { 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 ) { 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 ? ) { return ( error ) : Observable < T > => { console . error ( error ) ; console . log ( `${ operation } failed: ${ error . message }` ) ; return of ( result as T ) ; } ; } }