import { Injectable } from '@angular/core' ; import { HttpClient } from '@angular/common/http' ; import { Observable , BehaviorSubject } from 'rxjs' ; import 'rxjs/add/observable/timer' ; import 'rxjs/add/operator/takeWhile' ; import { environment } from 'src/environments/environment' ; @ Injectable ( ) export class DataproviderService { private backendAddress : string ; public dataSets : any = 0 ; public dataSet : any = 0 ; private alive : boolean ; private timer : Observable < number > ; private interval : number ; private dataSetsSubject = new BehaviorSubject < any > ( this . dataSets ) ; private dataSetSubject = new BehaviorSubject < any > ( this . dataSet ) ; private deliverSchema : any ; private deliverFeature : any ; private deliverPosition : any ; private deliverMeta : any ; constructor ( private http ) { this . alive = true ; this . interval = 10000 ; this . timer = Observable . timer ( 0 , this . interval ) ; this . backendAddress = environment . backendAddress === undefined ? 'http://localhost:4201' : environment . backendAddress ; this . timer . takeWhile ( ( ) => this . alive ) . subscribe ( ( ) => { this . http . get ( this . backendAddress + 'datasets' ) . subscribe ( ( data ) => { const newData = data ; if ( this . jsonEqual ( newData , this . dataSets ) ) { return ; } this . dataSets = newData ; this . setDataSets ( this . dataSets ) ; } ) ; } ) ; } private jsonEqual ( a , b ) { return JSON . stringify ( a ) === JSON . stringify ( b ) ; } public downloadDataSet ( name , version , position ) { this . http . get ( this . backendAddress + 'datasets/' + name + '/' + version + '/schema' ) . subscribe ( ( schemaData ) => { this . deliverSchema = schemaData ; this . http . get ( this . backendAddress + 'datasets/' + name + '/' + version + '/feature' ) . subscribe ( ( featureData ) => { this . deliverFeature = featureData ; this . http . get ( this . backendAddress + 'datasets/' + name + '/' + version + '/position/' + position ) . subscribe ( ( positionData ) => { this . deliverPosition = positionData ; this . http . get ( this . backendAddress + 'datasets/' + name + '/' + version + '/meta' ) . subscribe ( ( metaData ) => { this . deliverMeta = metaData ; this . doSetDownloadedData ( ) ; } , error => { this . doSetDownloadedData ( ) ; } ) ; } ) ; } ) ; } ) ; } private doSetDownloadedData ( ) { this . dataSet = { schema : this . deliverSchema , features : this . deliverFeature , positions : this . deliverPosition , meta : this . deliverMeta } ; this . setDataSet ( this . dataSet ) ; } private setDataSets ( value ) { this . dataSetsSubject . next ( value ) ; } public getDataSets ( ) { return this . dataSetsSubject . asObservable ( ) ; } private setDataSet ( value ) { this . dataSetSubject . next ( value ) ; } public getDataSet ( ) { return this . dataSetSubject . asObservable ( ) ; } }