environment.prod.ts
有关,但找不到任何使用它们来实现上述目标的示例。如果有人可以帮助我入门就太好了!environment.prod.ts
有关,但找不到任何使用它们来实现上述目标的示例。如果有人可以帮助我入门就太好了!不要硬编码URL地址。 请使用位于src/environments内的environment.prod.ts 和 environment.ts 文件。 对于本地主机,请在environment.ts文件中使用某个变量保存您的URL地址。
export const environment =
{
production: false,
API_URL: 'http://localhost:8080',
};
用于生产环境的配置文件位于environment.prod.ts中。
export const environment =
{
production: true,
API_URL: 'http://api.productionurl.com',
};
在您的代码中使用时,请导入该变量,
import { environment } from '../../environments/environment';
....
....
private API_URL= environment.API_URL;
每当您在用于生产环境的 Angular CLI 命令选项时,请注意。
ng build --env=prod
当前环境的文件内容将在构建过程中被覆盖。
构建系统默认使用开发环境(environment.ts
),但如果你运行ng build --env=prod
,则会使用environment.prod.ts
代替。
哪个环境映射到哪个文件的列表可以在.angular-cli.json
中找到。
如需更多查询,请参阅https://angular.io/guide/deployment
environment
的文件中并不会避免硬编码:shrug:。API URL应该通过环境变量设置。在名为environment
的文件中定义的变量不是环境变量。 - Sebastianindex.html
文件中。为了使其无缝工作,您必须使用变量占位符来精心制作您的index.html
文件。 - Sebastian在环境配置中添加API_URL是个好主意,但是如果你的API和客户端应用程序从同一个服务器或域名服务,你可以使用相对URL。这样做更容易设置并简化了您的构建过程。
下面是一些代码,它将存在于API服务中。
get(path: string, params: HttpParams = new HttpParams()): Observable<any> {
return this.http.get(`/api${path}`, { params })
.pipe(catchError(this.formatErrors));
}
ng serve
,并从localhost:43210上运行PHP、C#、Java等后端的API。您需要API_URL配置进行开发。 get(path: string, params: HttpParams = new HttpParams()): Observable<any> {
return this.http.get(`${environment.api_url}/api${path}`, { params })
.pipe(catchError(this.formatErrors));
}
使用容器的一种方法是在启动Web服务器之前解析环境文件。这需要假设您遵循良好的实践,即您不是通过ng
提供angular应用程序。
例如,一个基本的方法是使用所需配置构建index.html
,这只是一个例子,您可以根据自己的情况进行操作:
<script>
window.config = {
ENV_VAR1: 'ENV_VAR1_PLACEHOLDER',
ENV_VAR2: 'ENV_VAR2_PLACEHOLDER',
....
}
</script>
window.config
与实际环境变量。sed
进行此操作,或者如果您想专业一些,也可以使用[jq][1]
。index.html
将遵循12factors的dev-prod平价方法配置window.config
对象。docker run -it -e ENV_VAR1="我的开发值" ...
而对于生产环境,则是:
docker run -it -e ENV_VAR1="我的生产值" ...
window
可以在 environment.ts
文件中使用,并且您可以从那里导出值。由于 JavaScript 是运行时语言,因此如果该对象未定义,在构建时不会有影响。 - Sebastianexport const environment =
{
production: false,
API_URL: 'http://localhost:8080',
};
在生产环境中使用 environment.prod.ts 文件。
export const environment =
{
production: true,
API_URL: 'http://api.productionurl.com',
};
http://my.custom.domain.api.prod.com
或任何你想要的地址。 - chick3n0x07CC实现这一目标的一种可能方式是,在您的代码中基于 isDevMode()
定义不同的基本 URL。例如,
import { isDevMode } from '@angular/core';
// ...
let baseUrl: string;
if (isDevMode()) {
baseUrl = "http://localhost:8080/";
} else {
baseUrl = "http://api.myprodserver.com/";
}
// ...