import { Injectable, OnInit, PLATFORM_ID, Inject,InjectionToken } from '@angular/core'; import { isPlatformBrowser} from '@angular/common'; import { Http, Response, Headers, RequestOptions } from '@angular/http'; import { Observable, Subscription, BehaviorSubject } from 'rxjs/Rx'; import 'rxjs/add/operator/map'; import 'rxjs/add/operator/toPromise'; import { EnvProperties } from './env-properties'; import { DOCUMENT } from '@angular/platform-browser'; @Injectable() export class EnvironmentSpecificService { // export function createTranslateLoader(http: Http, @Inject('ORIGIN_URL') originUrl: string) { // return new TranslateHttpLoader(http, originUrl + './assets/i18n/', '.json'); public envSpecific: EnvProperties; public envSpecificNull: EnvProperties = null; testBrowser: boolean; private envSpecificSubject: BehaviorSubject = new BehaviorSubject(null); private propertiesUrl = "/assets/env-properties.json"; // private propertiesUrl = "https://beta.connect.openaire.eu/assets/env-properties.json"; constructor(private http: Http,@Inject(PLATFORM_ID) platformId: string,@Inject(DOCUMENT) private document: any) { this.testBrowser = isPlatformBrowser(platformId); if (this.testBrowser) { //this is only executed on the browser } } public loadEnvironment() { // Only want to do this once - if root page is revisited, it calls this again. if (this.envSpecific === null || this.envSpecific === undefined) { console.log('Loading '+ document.location.protocol +"//" + document.location.host+this.propertiesUrl); return this.http.get(document.location.protocol +"//" + document.location.host+this.propertiesUrl) .map((data) => data.json()) .toPromise(); } return Promise.resolve(this.envSpecificNull); } public subscribeEnvironment() { // Only want to do this once - if root page is revisited, it calls this again. if (this.envSpecific === null || this.envSpecific === undefined) { console.log('Loading env-properties.json'); return this.http.get(this.propertiesUrl) .map((data) => data.json()); } return Observable.of(this.envSpecific); } public setEnvProperties(es: EnvProperties) { // This has already been set so bail out. if (es === null || es === undefined) { return; } this.envSpecific = es; console.log(this.envSpecific); if (this.envSpecificSubject) { this.envSpecificSubject.next(this.envSpecific); } } /* Call this if you want to know when EnvProperties is set. */ public subscribe(caller: any, callback: (caller: any, es: EnvProperties) => void) { this.envSpecificSubject .subscribe((es) => { if (es === null) { return; } callback(caller, es); }); } }