在Angular中,如何在生产环境中创建可配置属性文件以读取属性? [英] In Angular how to Create a Configurable Property file to read a property, in production environment?

查看:36
本文介绍了在Angular中,如何在生产环境中创建可配置属性文件以读取属性?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我的应用程序中,我创建了appMessages.ts,其中包含一个变量,如:

In my application, I have created appMessages.ts, which holds a variable like:

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

我基本上是用它来进行REST调用的.在实际生产环境中,变量值会不断变化,并且需要可配置.如果我使用appMessages.ts,并使用

I`m basically using this to make REST calls. 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

ng build --prod

问题是,appMessages.ts不再可配置.有没有一种Angular方式来创建可配置的属性文件,可以根据当前的开发环境使用"my_url"对其进行动态配置?

Problem is, appMessages.ts is not configurable anymore. 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?

能否在部署产品后读取某种属性文件?

Can some kind of property file, which can be read after the product has been deployed?

推荐答案

您可以在src目录中创建以下config.json,然后使用APP_INITIALIZER提供程序.

You can create the following config.json in the src directory and then use the APP_INITIALIZER provider.

{
    "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;
}

这篇关于在Angular中,如何在生产环境中创建可配置属性文件以读取属性?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆