将基本URL在部署时传递给environment.ts文件。

huangapple go评论63阅读模式
英文:

Angular to pass the baseURL in the environment.ts file at deploy time

问题

我有一个Angular应用程序,其中environment.ts文件的baseURL硬编码如下。后端服务也部署在同一集群中,并且可以通过服务名称访问。

export const environment = {
  production: true,
  baseURL: 'http://<service>.<namespace>:<port>/api/v1/'
  ...
}

目前URL在environemnt.ts中硬编码,并且使用Dockerfile构建图像。

假设我想使用这个图像并部署为Kubernetes部署,是否有办法在运行时或动态地在清单中传递这个baseURL?请注意,我尝试部署的是httpd服务器而不是Nginx。

英文:

I have an Angular app where the environment.ts file is hard coded with the baseURL like below. The backend service is also deployed in same cluster and accessible with a service name.

export const environment = {
  production: true,
  baseURL: &#39;http://&lt;service&gt;.&lt;namespace&gt;:&lt;port&gt;/api/v1/&#39;
  ...
}

Currently the URL is hardcode in environemnt.ts and the image is built using Dockerfile.

Say, If I want to use the image and deploy as Kubernetes deployment, is there a way to pass this baseURL in the manifest during runtime or dynamically? Note, trying to deploy httpd server not Nginx.

答案1

得分: 2

不要在第一次使用environment.ts,因为当你构建应用程序时,它可以正常工作,但当你尝试在不同的环境中使用相同的代码库时(正如你自己已经发现的那样),它就不能正常工作。

在过去,我所做的是在environment.ts中使用某种令牌,例如:

export const environment = {
  production: true,
  baseURL: 'BASE_URL',
  ...
}

然后在部署过程中,我会在main.js文件中使用sed来替换BASE_URL。这并不是理想的方法,甚至有点不好,但正如你所期望的那样,它可以正常工作。

另一种方法是将配置外部化到一个单独的文件中,该文件将放置在部署旁边,例如env.js。这样的文件可以像应用程序的其他部分一样提供,因此在启动时,你可以获取它并通过你的设计中的“配置服务”提供它。

英文:

Dont use environment.ts in the first place as it works fine when you build your app, but not when you actually try to use the same codebase on different environments (as you have figured out yourself).

What I did in a past was to use some sort of tokens in the environment.ts eg

export const environment = {
  production: true,
  baseURL: &#39;BASE_URL&#39;
  ...
}

and then during the deployment I was literally replacing BASE_URL in the main.js file with sed. Its not ideal, even kind of bad, but it worked just fine as you expected.

Another way would be to externalize your config to a separate file that will be placed next to the deployment, eg env.js. Such file can be served as any other parts of your application, therfore on the bootstrap you will be able to fetch it and provide via "configuration service" of your design.

huangapple
  • 本文由 发表于 2023年8月4日 00:52:12
  • 转载请务必保留本文链接:https://go.coder-hub.com/76830135.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定