[英]In Angular how to Create a Configurable Property file to read a property, in production environment?
在我的應用程序中,我創建了appMessages.ts,其中包含如下變量:
export const appMessages = {
my_url: 'http://localhost:8080/myApp',
}
我基本上是用它來進行REST調用的。 在實際的生產環境中,變量值會不斷變化,需要進行配置。 如果我使用appMessages.ts並創建生產捆綁包,則使用
ng build --prod
問題是,appMessages.ts不再可配置。 有沒有一種Angular方式來創建可配置的屬性文件,可以根據當前的開發環境使用“ my_url”對其進行動態配置?
可以在部署產品后讀取某種屬性文件嗎?
您可以在src目錄中創建以下config.json,然后使用APP_INITIALIZER提供程序。
{
"myUrl": "http://172.22.251.207:20235"
}
app.module.ts
...
export function initConfig(config: AppConfigService) {
return () => config.load();
}
...
providers: [
{
provide: APP_INITIALIZER,
useFactory: initConfig,
deps: [AppConfigService],
multi: true
}]
...
app-config.service.ts
@Injectable({
providedIn: 'root'
})
export class AppConfigService {
private config: Config = null;
public configSubject: Subject<any> = new Subject<any>();
constructor(private http: HttpClient) { }
public load() {
return this.http.get(environment.deployUrl + 'config.json')
.toPromise()
.then((config: any) => {
this.config = config;
this.configSubject.next(this.config);
})
.catch((err: any) => {
console.error('ERROR: ' + err);
})
}
getMyUrl() {
return this.config.myUrl;
}
}
export class Config {
myUrl: string;
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.