1
|
import {Inject, Injectable, Optional} from '@angular/core';
|
2
|
import {HttpClient} from "@angular/common/http";
|
3
|
import {BehaviorSubject, of} from 'rxjs';
|
4
|
|
5
|
import {Request} from 'express';
|
6
|
import {REQUEST} from '@nguniversal/express-engine/tokens';
|
7
|
|
8
|
import {EnvProperties} from './env-properties';
|
9
|
import {properties} from "../../../../environments/environment";
|
10
|
|
11
|
@Injectable()
|
12
|
export class EnvironmentSpecificService {
|
13
|
|
14
|
public envSpecific: EnvProperties;
|
15
|
public domain: string;
|
16
|
private envSpecificSubject: BehaviorSubject<EnvProperties> = new BehaviorSubject<EnvProperties>(null);
|
17
|
private propertiesPath = "/assets/env-properties.json?v=2";
|
18
|
|
19
|
constructor(private http: HttpClient, @Optional() @Inject(REQUEST) private request: Request) {
|
20
|
properties.domain = this.getDomain();
|
21
|
}
|
22
|
|
23
|
public loadEnvironment() {
|
24
|
this.envSpecific = properties;
|
25
|
return Promise.resolve(this.envSpecific);
|
26
|
}
|
27
|
|
28
|
public subscribeEnvironment() {
|
29
|
// 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
|
}
|
36
|
|
37
|
getDomain() {
|
38
|
var domain = "";
|
39
|
if (typeof document == 'undefined') {
|
40
|
domain = this.request.get('host').split(":")[0];
|
41
|
} else {
|
42
|
domain = document.location.hostname;
|
43
|
}
|
44
|
return domain;
|
45
|
}
|
46
|
|
47
|
public setEnvProperties(es: EnvProperties) {
|
48
|
// This has already been set so bail out.
|
49
|
if (es === null || es === undefined) {
|
50
|
return;
|
51
|
}
|
52
|
this.envSpecific = es;
|
53
|
if (this.envSpecificSubject) {
|
54
|
this.envSpecificSubject.next(this.envSpecific);
|
55
|
}
|
56
|
}
|
57
|
|
58
|
/*
|
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
|
this.envSpecificSubject
|
63
|
.subscribe((es) => {
|
64
|
if (es === null) {
|
65
|
return;
|
66
|
}
|
67
|
callback(caller, es);
|
68
|
});
|
69
|
}
|
70
|
}
|