1
|
import { Injectable, OnInit, PLATFORM_ID, Inject } from '@angular/core';
|
2
|
import { isPlatformBrowser} from '@angular/common';
|
3
|
import { Http, Response, Headers, RequestOptions } from '@angular/http';
|
4
|
import { Observable, Subscription, BehaviorSubject } from 'rxjs/Rx';
|
5
|
import 'rxjs/add/operator/map';
|
6
|
import 'rxjs/add/operator/catch';
|
7
|
import 'rxjs/add/operator/toPromise';
|
8
|
|
9
|
import { EnvProperties } from './env-properties';
|
10
|
|
11
|
@Injectable()
|
12
|
export class EnvironmentSpecificService {
|
13
|
|
14
|
public envSpecific: EnvProperties;
|
15
|
public envSpecificNull: EnvProperties = null;
|
16
|
testBrowser: boolean;
|
17
|
private envSpecificSubject: BehaviorSubject<EnvProperties> = new BehaviorSubject<EnvProperties>(null);
|
18
|
private propertiesUrl = (process.env.PROP_URL)?process.env.PROP_URL:"./assets/env-properties.json";
|
19
|
constructor(private http: Http,@Inject(PLATFORM_ID) platformId: string) {
|
20
|
this.testBrowser = isPlatformBrowser(platformId);
|
21
|
if (this.testBrowser) {
|
22
|
//this is only executed on the browser
|
23
|
}
|
24
|
console.log('EnvironmentSpecificService created ' +this.testBrowser);
|
25
|
/*
|
26
|
|
27
|
down vote
|
28
|
|
29
|
|
30
|
import { PLATFORM_ID, Inject } from '@angular/core';
|
31
|
import { isPlatformBrowser} from '@angular/common';
|
32
|
...
|
33
|
export class MyComponent {
|
34
|
...
|
35
|
testBrowser: boolean;
|
36
|
constructor(
|
37
|
@Inject(PLATFORM_ID) platformId: string) {
|
38
|
this.testBrowser = isPlatformBrowser(platformId);
|
39
|
if (this.testBrowser) {
|
40
|
//this is only executed on the browser
|
41
|
}
|
42
|
}
|
43
|
*/
|
44
|
}
|
45
|
|
46
|
public loadEnvironment() {
|
47
|
// Only want to do this once - if root page is revisited, it calls this again.
|
48
|
if (this.envSpecific === null || this.envSpecific === undefined) {
|
49
|
console.log('Loading env-properties.json');
|
50
|
|
51
|
return this.http.get(this.propertiesUrl)
|
52
|
.map((data) => data.json())
|
53
|
.toPromise<EnvProperties>();
|
54
|
}
|
55
|
|
56
|
return Promise.resolve(this.envSpecificNull);
|
57
|
}
|
58
|
|
59
|
public setEnvProperties(es: EnvProperties) {
|
60
|
// This has already been set so bail out.
|
61
|
if (es === null || es === undefined) {
|
62
|
return;
|
63
|
}
|
64
|
|
65
|
this.envSpecific = es;
|
66
|
console.log(this.envSpecific);
|
67
|
|
68
|
if (this.envSpecificSubject) {
|
69
|
this.envSpecificSubject.next(this.envSpecific);
|
70
|
}
|
71
|
}
|
72
|
|
73
|
/*
|
74
|
Call this if you want to know when EnvProperties is set.
|
75
|
*/
|
76
|
public subscribe(caller: any, callback: (caller: any, es: EnvProperties) => void) {
|
77
|
this.envSpecificSubject
|
78
|
.subscribe((es) => {
|
79
|
if (es === null) {
|
80
|
return;
|
81
|
}
|
82
|
callback(caller, es);
|
83
|
});
|
84
|
}
|
85
|
}
|