Angular CLI:在构建时更改REST API URL [英] Angular CLI: Change REST API URL on build
问题描述
我想从我的REST API URL中删除本地服务器前缀(例如, http://localhost:8080 )在进行生产生产时(ng build --prod
).
I want to remove my local server prefix from my REST API URLs (example, http://localhost:8080) when building for production (ng build --prod
).
我知道这与环境文件environment.prod.ts
有关,但是找不到使用它们来实现上述目标的任何示例.
I get that it's something to do with the environment file environment.prod.ts
, but can't find any examples of making use of them to achieve the aforementioned.
如果有人帮助我入门,那就太好了!
Would be great if someone helps me get started!
推荐答案
请勿对网址进行硬编码. 使用src/environments内部的 environment.prod.ts 和 environment.ts 文件. 对于本地主机,在environment.ts文件中,使用一些变量来保存您的网址.
Dont hard code the URL. Use environment.prod.ts and environment.ts files which are inside src/environments. for localhost, in environment.ts file use some variable to save your url.
export const environment =
{
production: false,
API_URL: 'http://localhost:8080',
};
用于生产,在environment.prod.ts
for production, in environment.prod.ts
export const environment =
{
production: true,
API_URL: 'http://api.productionurl.com',
};
在代码中使用时,导入变量
When using in your code import the variable,
import { environment } from '../../environments/environment';
....
....
private API_URL= environment.API_URL;
当您用于生产时,请使用angular cli命令选项
whenever your are using for production use angular cli command option
ng build --env=prod
当前环境的文件内容将在构建过程中覆盖这些内容.
构建系统默认为使用environment.ts
的dev环境,但是如果您这样做,
ng build --env=prod
,然后将使用environment.prod.ts
.
可以在.angular-cli.json
中找到哪些环境映射到哪个文件的列表.
The file contents for the current environment will overwrite these during build.
The build system defaults to the dev environment which uses environment.ts
, but if you do
ng build --env=prod
then environment.prod.ts
will be used instead.
The list of which env maps to which file can be found in .angular-cli.json
.
有关更多查询,请参考, https://angular.io/guide/deployment
For more queries refer, https://angular.io/guide/deployment
这篇关于Angular CLI:在构建时更改REST API URL的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!