在生产版本Angular 4中访问环境变量 [英] Access environment variables in production build Angular 4

查看:94
本文介绍了在生产版本Angular 4中访问环境变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想部署一个带有可配置api URL的有角度应用程序的生产版本,以供用户进行测试.我使用environment.ts,但在生产构建后,我不知道如何配置变量.

I want to deploy a production build of angular app with a configurable api url for the user to test it out. I use the environment.ts but after the production build, I do not know how to configure the variables.

需要采取什么方法?

推荐答案

您是否正在使用Angular-CLI?那应该很容易.你有这样的东西:

Are you using Angular-CLI? It should be easy, then. You have something like this:

src/
  app/
  environment/
    environment.ts
    environment.prod.ts

只需将不同的url放入environment.prod.ts中,您的prod版本将获得第二个url.例如.假设您的environment.ts看起来像这样:

Simply put different url in environment.prod.ts and your prod build gets a second url. E.g. let's say your environment.ts looks like this:

{
  "production": false,
  "apiUrl": "http://localhost:8080"
}

将此内容放入environment.prod.ts:

{
  "production": true,
  "apiUrl": "https://example.com/api"
}

您可以设置更多的环境,检查.angular-cli.json的相应部分以及angular-cli repo.

You can setup more environments, check that section of .angular-cli.json and angular-cli repo.

编辑:根据您的评论,您需要更多.

As per your comment, you want more.

是的,但是在构建之后仍然无法配置,不是吗?因为我不知道用户要使用什么url,所以我希望在部署构建后从外部对其进行配置.

Yes but still this is not configurable after the build isn't it? Because I don't know what url the user want to use therefore I want to make it configurable from the outside after deploying the build.

让我们继续这种情况.我们有一个后端客户端:

Let's continue this scenario further. Let's have a backend client:

import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { apiUrl } from '../environment/environment.ts';
@Injectable()
export class BackendService {
    backendUrl: string = apiUrl;      

    constructor(private httpClient: HttpClient) {}

    get(endpoint: string, params: any): Observable<any> {
      const url= `${this.backendUrl}/${endpoint}`;
      return this.httpClient.get(url, params);
    }
}

简体,但是可以.默认情况下,您设置自己的URL.但是您的组件可以动态设置网址,并从该网址中获取其他信息.

Simplified, but works. By default, you set your own URL. But your components can set the url on the fly, and get other things from that url.

现在,下一步就是提供您拥有的后端.这可以是预配置的数组,也可以让客户端自由输入URL(只需输入框).您可以具有执行此操作的组件,并在此处配置此服务.您可能还应该为适当的"后端提供单独的服务,例如您的身份验证谎言.但这真的取决于您的情况.

Now, the next step would be, offering which backends you have. This can be a preconfigured array, or you can let the client enter the url freely (simply input box). You can have a component that does that, and configures this service here. You should probably also have a separate service for your "proper" backend, where, e.g. your auth lies. But this all really depends on your scenario.

这篇关于在生产版本Angular 4中访问环境变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆