Project

General

Profile

1 58888 k.triantaf
import {Inject, Injectable, Optional} from '@angular/core';
2 55964 argiro.kok
import {HttpClient} from "@angular/common/http";
3 58882 k.triantaf
import {BehaviorSubject, of} from 'rxjs';
4 50586 argiro.kok
5 55964 argiro.kok
import {Request} from 'express';
6
import {REQUEST} from '@nguniversal/express-engine/tokens';
7
8 58882 k.triantaf
import {EnvProperties} from './env-properties';
9
import {properties} from "../../../../environments/environment";
10 50586 argiro.kok
11
@Injectable()
12
export class EnvironmentSpecificService {
13 58907 k.triantaf
14 50586 argiro.kok
  public envSpecific: EnvProperties;
15 54948 argiro.kok
  public domain: string;
16 50586 argiro.kok
  private envSpecificSubject: BehaviorSubject<EnvProperties> = new BehaviorSubject<EnvProperties>(null);
17 57791 argiro.kok
  private propertiesPath = "/assets/env-properties.json?v=2";
18 58907 k.triantaf
19 58882 k.triantaf
  constructor(private http: HttpClient, @Optional() @Inject(REQUEST) private request: Request) {
20
    properties.domain = this.getDomain();
21 50586 argiro.kok
  }
22 58882 k.triantaf
23 50586 argiro.kok
  public loadEnvironment() {
24 58907 k.triantaf
    this.envSpecific = properties;
25
    return Promise.resolve(this.envSpecific);
26 54948 argiro.kok
  }
27 58907 k.triantaf
28 51261 argiro.kok
  public subscribeEnvironment() {
29 58907 k.triantaf
    // Only want to do this once - if root page is revisited, it calls this again.
30
    if (this.envSpecific === null || this.envSpecific === undefined) {
31
      this.envSpecific = properties;
32
    }
33
    // console.log('subscribeEnvironment: already loaded  ');
34
    return of(this.envSpecific);
35 51261 argiro.kok
  }
36 58907 k.triantaf
37
  getDomain() {
38
    var domain = "";
39 54948 argiro.kok
    if (typeof document == 'undefined') {
40 55964 argiro.kok
      domain = this.request.get('host').split(":")[0];
41 58907 k.triantaf
    } else {
42 55964 argiro.kok
      domain = document.location.hostname;
43 58907 k.triantaf
    }
44
    return domain;
45 54948 argiro.kok
  }
46 58907 k.triantaf
47 50586 argiro.kok
  public setEnvProperties(es: EnvProperties) {
48
    // This has already been set so bail out.
49
    if (es === null || es === undefined) {
50 58907 k.triantaf
      return;
51 50586 argiro.kok
    }
52
    this.envSpecific = es;
53
    if (this.envSpecificSubject) {
54 58907 k.triantaf
      this.envSpecificSubject.next(this.envSpecific);
55 50586 argiro.kok
    }
56
  }
57 58907 k.triantaf
58 50586 argiro.kok
  /*
59
    Call this if you want to know when EnvProperties is set.
60
  */
61
  public subscribe(caller: any, callback: (caller: any, es: EnvProperties) => void) {
62 58907 k.triantaf
    this.envSpecificSubject
63
      .subscribe((es) => {
64
        if (es === null) {
65
          return;
66
        }
67
        callback(caller, es);
68
      });
69 50586 argiro.kok
  }
70
}