[英]Angular 5: Run Constructor before beeing injected
我有一个带有全局变量的文件:
@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';
}
}
目前,我的API调用失败,因为尚未设置变量。 有没有一种方法只能在构造函数运行时注入此服务,或者我必须使用Observables?
您为什么不将这些保存在environment.ts中 ? 您还可以为prod
, dev
等保留不同的环境。
export const environment = {
production: false,
envName: 'local',
baseUrl: '',
proxyUrl: '',
servicesUrl: ''
};
并为您服务:
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`)
}
}
本身并没有解决。 我现在这样使用它:
@Injectable()
export class Globals {
/** API URLS */
public baseURL:string = '';
public loginURL:string = 'rest/login';
public proxyURL:string = 'rest/proxy';
public servicesURL:string = 'rest/serviceRegistry';
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.