import { EventEmitter , Injectable } from '@angular/core' ; import { Http , URLSearchParams } from '@angular/http' ; import { Observable } from 'rxjs/Observable' ; import 'rxjs/add/operator/map' ; export class Product { constructor ( public id , public title , public price , public rating , public description , public categories ) { } } export class Review { constructor ( public id , public productId , public timestamp , public user , public rating , public comment ) { } } export interface ProductSearchParams { title : string ; minPrice : number ; maxPrice : number ; } @ Injectable ( ) export class ProductService { searchEvent : EventEmitter < any > = new EventEmitter ( ) ; constructor ( private http ) { } search ( params ) { return this . http . get ( '/products' , { search : encodeParams ( params ) } ) . map ( response => response . json ( ) ) ; } getProducts ( ) { return this . http . get ( '/products' ) . map ( response => response . json ( ) ) ; } getProductById ( productId ) { return this . http . get ( `/products/${ productId }` ) . map ( response => response . json ( ) ) ; } getReviewsForProduct ( productId ) { return this . http . get ( `/products/${ productId }/reviews` ) . map ( response => response . json ( ) ) . map ( reviews => reviews . map ( ( r ) => new Review ( r . id , r . productId , new Date ( r . timestamp ) , r . user , r . rating , r . comment ) ) ) ; } getAllCategories ( ) { return [ 'Books' , 'Electronics' , 'Hardware' ] ; } } /**
 * 객체를 쿼리스트링으로 변환하는 함수
 */ function encodeParams ( params ) { const queryStr = new URLSearchParams ( ) ; if ( params . title !== null && params . title !== '' ) { queryStr . append ( 'title' , params . title ) ; } if ( params . price !== null ) { queryStr . append ( 'price' , params . price ) ; } if ( params . category !== - 1 ) { queryStr . append ( 'category' , params . category ) ; } return queryStr ; }