import { Injectable } from '@angular/core' ; import { Http } from '@angular/http' ; import { Movie , MovieFields } from '../models/movie' ; import { Observable } from 'rxjs/Rx' ; import 'rxjs/Rx' ; @ Injectable ( ) export class IMDBAPIService { private moviesUrl : string = "app/marvel-cinematic-universe.json" ; constructor ( private http ) { } param { number } id return { Promise < Movie > } public fecthOneById ( id ) { console . log ( 'fecthOneById' , id ) ; return this . http . get ( this . moviesUrl ) . flatMap ( res => res . json ( ) . movies ) . filter ( ( movie ) => { console . log ( "filter" , movie ) ; return ( movie . movie_id === id ) ; } ) . toPromise ( ) . then ( ( movie ) => { console . log ( "map" , movie ) ; return new Movie ( movie . movie_id , movie . title , movie . phase , movie . category_name , movie . release_year , movie . running_time , movie . rating_name , movie . disc_format_name , movie . number_discs , movie . viewing_format_name , movie . aspect_ratio_name , movie . status , movie . release_date , movie . budget , movie . gross , movie . time_stamp ) ; } ) ; } /**
     * Private member storing pending promises
     */ private promises : Promise < Movie [ ] > [ ] = [ ] ; param { MovieFields } field param { any } value return { IMDBAPIService } public byField ( field , value ) { this . promises . push ( this . fetchByField ( field , value ) ) ; return this ; } param { MovieFields } field param { any } value return { IMDBAPIService } public or ( field , value ) { return this . byField ( field , value ) ; } return { Promise < Movie [ ] > } public fetch ( ) { return Promise . all ( this . promises ) . then ( ( results ) => { return [ ] . concat . apply ( [ ] , results ) ; } ) ; } public fetchByField ( field , value ) { console . log ( 'fetchByField' , field , value ) ; return this . http . get ( this . moviesUrl ) . map ( res => res . json ( ) . movies . filter ( ( movie ) => { return ( movie [ MovieFields [ field ] ] === value ) ; } ) ) . toPromise ( ) . then ( ( jsonMovies ) => { console . log ( "map" , jsonMovies ) ; let movies = [ ] ; for ( var i = 0 ; i < jsonMovies . length ; i ++ ) { movies . push ( new Movie ( jsonMovies [ i ] . movie_id , jsonMovies [ i ] . title , jsonMovies [ i ] . phase , jsonMovies [ i ] . category_name , jsonMovies [ i ] . release_year , jsonMovies [ i ] . running_time , jsonMovies [ i ] . rating_name , jsonMovies [ i ] . disc_format_name , jsonMovies [ i ] . number_discs , jsonMovies [ i ] . viewing_format_name , jsonMovies [ i ] . aspect_ratio_name , jsonMovies [ i ] . status , jsonMovies [ i ] . release_date , jsonMovies [ i ] . budget , jsonMovies [ i ] . gross , jsonMovies [ i ] . time_stamp ) ) ; } return movies ; } ) ; } }