繁体   English   中英

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

[英]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.

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