import { HttpClient } from '@angular/common/http' ; import { Injectable } from '@angular/core' ; import { Observable } from 'rxjs/Observable' ; import { of } from 'rxjs/observable/of' ; import { map , switchMap } from 'rxjs/operators' ; import { Product } from '@state/product/product.model' ; @ Injectable ( ) export class ProductService { private productsUrl = 'app/products' ; constructor ( private httpClient ) { } getProducts ( ) { return this . httpClient . get < Product [ ] > ( this . productsUrl ) ; } getProduct ( id ) { return this . getProducts ( ) . pipe ( map ( products => products . find ( product => product . id === id ) ) ) ; } save ( product ) { if ( product . id ) { return this . put ( product ) ; } return this . post ( product ) ; } delete ( product ) { const url = `${ this . productsUrl }/${ product . id }` ; return this . httpClient . delete < void > ( url ) . pipe ( switchMap ( ( ) => of ( product ) ) ) ; } private post ( product ) { return this . httpClient . post < Product > ( this . productsUrl , product ) ; } private put ( product ) { const url = `${ this . productsUrl }/${ product . id }` ; return this . httpClient . put ( url , product ) . pipe ( switchMap ( ( ) => of ( product ) ) ) ; } }