简体   繁体   中英

Angular 5: Run Constructor before beeing injected

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?

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`)
  }

}

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';
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM