0

I have a file with global variables:

@Injectable()
export class Globals {
  public baseURL:string;
  public loginURL:string;
  public proxyURL:string;
  public servicesURL:string;

  constructor(platformLocation: PlatformLocation) {
    this.baseURL = (platformLocation as any).location.href;
    this.loginURL = this.baseURL + 'rest/login';
    this.proxyURL = this.baseURL + 'rest/proxy';
    this.servicesURL = this.baseURL + 'rest/serviceRegistry';
  }
}

At the moment my API-Calls fail because the variables aren't set yet. Is there a way to only inject this service when the constructor is run or do I have to use Observables?

Heretic Monkey
  • 11,687
  • 7
  • 53
  • 122
NDDT
  • 445
  • 1
  • 10
  • 27

2 Answers2

0

Why don't you keep these in environment.ts? You can also keep different environments for prod, dev etc.

export const environment = {
  production: false,
  envName: 'local',
  baseUrl: '',
  proxyUrl: '',
  servicesUrl: ''
};

And in your service:

import { Injectable } from '@angular/core';
import { environment } from '../../environments/environment';
import { HttpClient } from '@angular/common/http';

@Injectable()
export class MyService {

  constructor(private http: HttpClient) { }

  getData() {
    return this.http.get(`${environment.server}/remaining/path`)
  }

}
sabithpocker
  • 15,274
  • 1
  • 42
  • 75
  • but then this would be static and if the url changes I have to change this manually – NDDT Mar 20 '18 at 14:44
  • So your API call URL itself is dynamic? From where and how are you getting those dynamic values? – sabithpocker Mar 20 '18 at 14:45
  • we have a lot of services running (20+), they are accessed through a proxy, and the list of services with their current url is provided by the proxy – NDDT Mar 20 '18 at 14:52
  • but here I only set the url of the proxy to retrieve that list – NDDT Mar 20 '18 at 14:53
0

Didnt solve it per se. I'm using it like this now:

@Injectable()
export class Globals {
  /** API URLS */
  public baseURL:string = '';
  public loginURL:string = 'rest/login';
  public proxyURL:string = 'rest/proxy';
  public servicesURL:string = 'rest/serviceRegistry';
}
NDDT
  • 445
  • 1
  • 10
  • 27