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

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

问题描述

我想使用可配置的 api url 部署 angular 应用程序的生产版本,供用户进行测试.我使用的是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.但是您的组件可以即时设置 url,并从该 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天全站免登陆