import {Inject, Injectable, Optional} from '@angular/core'; import {HttpClient} from "@angular/common/http"; import {BehaviorSubject, of} from 'rxjs'; import {Request} from 'express'; import {REQUEST} from '@nguniversal/express-engine/tokens'; import {EnvProperties} from './env-properties'; import {properties} from "../../../../environments/environment"; @Injectable() export class EnvironmentSpecificService { public envSpecific: EnvProperties; public domain: string; private envSpecificSubject: BehaviorSubject = new BehaviorSubject(null); private propertiesPath = "/assets/env-properties.json?v=2"; constructor(private http: HttpClient, @Optional() @Inject(REQUEST) private request: Request) { properties.domain = this.getDomain(); } public loadEnvironment() { this.envSpecific = properties; return Promise.resolve(this.envSpecific); } public subscribeEnvironment() { // Only want to do this once - if root page is revisited, it calls this again. if (this.envSpecific === null || this.envSpecific === undefined) { this.envSpecific = properties; } // console.log('subscribeEnvironment: already loaded '); return of(this.envSpecific); } getDomain() { var domain = ""; if (typeof document == 'undefined') { domain = this.request.get('host').split(":")[0]; } else { domain = document.location.hostname; } return domain; } public setEnvProperties(es: EnvProperties) { // This has already been set so bail out. if (es === null || es === undefined) { return; } this.envSpecific = es; 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); }); } }