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



在我的应用程序中,我创建了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;
}

最新更新