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!
推荐答案
不要硬编码 URL.使用 src/environments 中的 environment.prod.ts 和 environment.ts 文件.对于本地主机,在 environment.ts 文件中使用一些变量来保存您的 url.
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',
};
在代码中使用 import 变量时,
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
的开发环境,但如果你这样做ng build --env=prod
然后将使用 environment.prod.ts
代替.可以在 .angular-cli.json
中找到哪个 env 映射到哪个文件的列表.
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
这篇关于Angular CLI:在构建时更改 REST API URL的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!