import { Injectable } from '@angular/core' ; import { HttpClient } from '@angular/common/http' ; import { Observable , throwError } from 'rxjs' ; import { catchError , tap , map } from 'rxjs/operators' ; import { IMovie } from './movie' ; @ Injectable ( { providedIn : 'root' } ) export class MovieService { private moviesUrl = './api/movies/movies.json' ; constructor ( private http ) { } getMovies ( ) { return this . http . get < IMovie [ ] > ( this . moviesUrl ) . pipe ( tap ( data => console . log ( JSON . stringify ( data ) ) ) , catchError ( this . handleError ) ) ; } getMovie ( id ) { return this . http . get < IMovie [ ] > ( this . moviesUrl ) . pipe ( map ( ( movies ) => this . handleMap ( movies , id ) ) , tap ( data => console . log ( 'Data: ' + JSON . stringify ( data ) ) ) , catchError ( this . handleError ) ) ; } private handleError ( err ) { const errorMessage = `Server returned code: ${ err . status }, error message is: ${ err . message }` ; console . error ( errorMessage ) ; return throwError ( errorMessage ) ; } private handleMap ( movies , id ) { if ( id === 0 ) { return { id : 0 , approvalRating : null , description : '' , director : '' , imageurl : '' , mpaa : '' , price : null , releaseDate : '' , starRating : null , title : '' } ; } return movies . find ( m => m . id === id ) ; } }