import { HttpClient , HttpErrorResponse } from '@angular/common/http' ; import { Injectable } from '@angular/core' ; import { BehaviorSubject , Observable , of } from 'rxjs' ; import { catchError } from 'rxjs/operators' ; /**
 * Retreives xml contents from a product via http calls, and parses contents
 */ @ Injectable ( ) export class ContentsXmlService { contents$ : BehaviorSubject < any > = new BehaviorSubject < any > ( null ) ; constructor ( public httpClient ) { } param product get ( product ) { try { const content = product . contents [ 'contents.xml' ] ; const options = { responseType : 'text' as 'text' } ; this . httpClient . get ( content . url , options ) . pipe ( catchError ( this . handleError ( ) ) ) . subscribe ( response => { this . contents$ . next ( this . parseResponse ( response , product ) ) ; } ) ; } catch ( e ) { this . contents$ . next ( null ) ; } } param file returns parseFile ( file , product ) { if ( file . getAttribute ( 'refid' ) ) { throw new Error ( 'file element with refid' ) ; } const id = file . getAttribute ( 'id' ) ; const title = file . getAttribute ( 'title' ) ; const captionElement = file . querySelector ( 'caption' ) ; const caption = captionElement ? captionElement . textContent : '' ; const formats = Array . prototype . map . call ( file . querySelectorAll ( 'format' ) , format => this . parseFormat ( format , product ) ) ; return { caption : caption , formats : formats , id : id , title : title } ; } param format param product returns parseFormat ( format , product ) { let result , content ; try { const href = format . getAttribute ( 'href' ) ; const type = format . getAttribute ( 'type' ) ; result = { href : href , length : 0 , type : type , url : null } ; content = product . contents [ href ] || { } ; result . url = content . url ; result . length = content . length ; } catch ( e ) { } return result ; } param response param product returns parseResponse ( response , product ) { const xml = new DOMParser ( ) . parseFromString ( response , 'text/xml' ) ; return Array . prototype . map . call ( xml . querySelectorAll ( 'contents > file' ) , file => this . parseFile ( file , product ) ) ; } returns private handleError ( ) { return ( error ) : Observable < any > => { return of ( null ) ; } ; } }