Angular 5: 运行 注入前的构造函数
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';
}
我有一个包含全局变量的文件:
@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';
}