简体   繁体   English

在Angular中,如何在生产环境中创建可配置属性文件以读取属性?

[英]In Angular how to Create a Configurable Property file to read a property, in production environment?

In my application, I have created appMessages.ts, which holds a variable like: 在我的应用程序中,我创建了appMessages.ts,其中包含如下变量:

export const appMessages = {
    my_url: 'http://localhost:8080/myApp',
}

I`m basically using this to make REST calls. 我基本上是用它来进行REST调用的。 In real production environment, The variable value keeps changing, and needs to be configurable. 在实际的生产环境中,变量值会不断变化,需要进行配置。 If I use appMessages.ts, and create a production bundle, using 如果我使用appMessages.ts并创建生产捆绑包,则使用

ng build --prod

Problem is, appMessages.ts is not configurable anymore. 问题是,appMessages.ts不再可配置。 Is there an Angular way to create a configurable property file, which can be configured dynamically with 'my_url' depending on the current development environment? 有没有一种Angular方式来创建可配置的属性文件,可以根据当前的开发环境使用“ my_url”对其进行动态配置?

Can some kind of property file, which can be read after the product has been deployed? 可以在部署产品后读取某种属性文件吗?

You can create the following config.json in the src directory and then use the APP_INITIALIZER provider. 您可以在src目录中创建以下config.json,然后使用APP_INITIALIZER提供程序。

{
    "myUrl": "http://172.22.251.207:20235"
}

app.module.ts 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 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.

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