import { Injectable } from '@angular/core' ; import { Http , URLSearchParams } from '@angular/http' ; import { Book , BookKind , Publisher , Author } from '../models/book' ; import { Observable } from 'rxjs/Rx' ; @ Injectable ( ) export class BooksService { private bookKinds : BookKind [ ] ; constructor ( private http ) { } getBooks ( ) { return < Observable < Book [ ] > > this . http . get ( '/books/' ) . map ( res => < { list : Book [ ] ; } > res . json ( ) ) . map ( data => < Book [ ] > data . list ) ; } getBooksByTitle ( title ) { let parameters = new URLSearchParams ( ) ; parameters . set ( 'title' , title ) ; return this . http . get ( '/books/' , { search : parameters } ) . map ( res => res . json ( ) ) ; } getBookAuthors ( bookId ) { return this . http . get ( `/books/${ bookId }` ) . map ( res => res . json ( ) ) . flatMap ( ( book ) => { return Observable . forkJoin ( < Observable < Author > [ ] > book . authors . map ( ( author ) => { return this . http . get ( `/authors/${ author . author }` ) . map ( res => < Author > res . json ( ) ) ; } ) ) ; } ) ; } getBookPublisher ( bookId ) { return this . http . get ( `/books/${ bookId }` ) . map ( res => < Book > res . json ( ) ) . flatMap ( ( book ) => { return this . http . get ( `/publishers/${ book . publisher . publisher }` ) . map ( res => < Publisher > res . json ( ) ) ; } ) ; } getBookWithDetails ( bookId ) { return this . http . get ( `/books/${ bookId }` ) . map ( res => res . json ( ) ) . flatMap ( ( book ) => { return Observable . forkJoin ( Observable . of ( book ) ) ; } ) . map ( ( bookDetails ) => { let book = bookDetails [ 0 ] ; console . log ( book ) ; return book ; } ) ; } addBook ( book ) { return this . http . post ( '/books/' , book ) ; } getBookKinds ( ) { if ( this . bookKinds ) { return Observable . of ( this . bookKinds ) ; } else { return this . http . get ( '/bookkinds' ) . map ( res => res . json ( ) ) ; } } }