如何在有角度的版本> = 2中使用环境变量 [英] how can we use environment variable in angular version >=2
问题描述
我现在正在阅读angular4文档,并注意到有一个文件夹,环境,如果我们使用env = prod进行构建,则在该文件夹下有多个环境文件,例如environment.ts,environment.prod.ts. ,则将使用prod环境变量. 现在我有一个问题,如何从代码中获取环境变量?我在Google上搜索了很多文档,对此没有提及. 谁能告诉我如何获取环境变量值? 谢谢
I am now reading the angular4 doc, and noticed, there is one folder, environments, and under which, there are multiple environment files, such as environment.ts, environment.prod.ts, if we build using env=prod, then prod environments variable will be used. Now I have one question, how can I get environment variable from the code? I googled the doc quite a lot and there is no mention about this. Can anyone help to tell me how to obtain environment variable values? Thanks
推荐答案
如果使用的是CLI,则将其放在
.angular-cli.json
文件中. (从角度6开始,.angular-cli.json
文件重命名为.angular.json
)
If you are using CLI then in
.angular-cli.json
file, place this code. (From angular 6 onward,.angular-cli.json
file is renamed to.angular.json
)
"environments": {
"dev": "environments/environment.ts",
"prod": "environments/environment.prod.ts"
}
在开发环境文件中,您可以编写
In dev environment file, you can write
export const environment = {
production: false,
url: 'http://something.com'
};
在产品环境文件中,您可以编写
And in prod environment file, you can write
export const environment = {
production: true,
url: 'http://something.com'
}
在组件或服务中,您可以使用like
In components or services, you can use like
import {environment} from '../../environments/environment';
environment.url;
您可以命令:
ng serve --dev // Or
ng serve --prod
注意:您应该直接在应用程序目录中具有环境目录,并且两个环境文件都应该在该目录中.
Note: you should have environments directory directly in app directory and both environment files should be there.
这篇关于如何在有角度的版本> = 2中使用环境变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!