【问题标题】:How to reuse the build for an Angular project如何为 Angular 项目重用构建
【发布时间】:2017-09-12 11:06:22
【问题描述】:

我如何重用我的 Angular 构建,这样我就不必为每个特定环境构建?

我们需要找到一种方法来在 Angular 中操作运行时环境!

我们对每个环境都有设置,我们使用 NG build --env=dev 并为开发环境构建。如何更改 QA、UAT 和生产环境中的配置?

工具集:.Net Visual Studio Team Services,Angular 2

有没有办法在运行时做到这一点?我们是否受困于构建时间/设计时间?

我们还可以考虑根据带有后缀的 url 选择环境吗? https://company-fancyspawebsite-qa.azurewebsites.net

PS:我们正在为每个环境使用 Angular 2 环境文件夹和应用程序设置文件。

【问题讨论】:

  • 每个环境有什么样的角度配置?你能分享更多细节吗?
  • 查看thisthisthis 了解如何做到这一点的几种方法。
  • 我们正在为每个环境使用 Angular 2 环境文件夹和 appsettings 文件。

标签: angular configuration continuous-integration angular2-routing


【解决方案1】:

我使用配置服务在运行时提供可编辑的配置设置。 (这是使用 angular-cli)

config.service.ts

import { Injectable } from '@angular/core';
import { Http, Headers, RequestOptions, Response } from '@angular/http';

export interface Config {
    PageSize: number;
    EnableConsoleLogging: boolean;
    WebApiBaseUrl: string;
}

@Injectable()
export class ConfigService {
    private config: Config;

    constructor(private http: Http) { }

    public getConfigSettings(): Config {
        if (!this.config) {
            var Httpreq = new XMLHttpRequest();
            Httpreq.open("GET", 'config.json', false);
            Httpreq.send(null);

            this.config = JSON.parse(Httpreq.responseText);

            if (this.config.EnableConsoleLogging)
                console.log("Config loaded", this.config);
        }

        return this.config;
    }
}

config.json 位于我的 src 文件夹中

{
  "WebApiBaseUrl": "http://myWebApi.com",
  "EnableConsoleLogging": true,
  "PageSize": 10
}

将 config.json 添加到 .angular-cli.json 中的资产

{
  },
  "apps": [
    {
      "assets": [
        "config.json"
      ]
    }
  }
}

如何使用它

export class MyComponent {
    private config: Config;

    constructor(private configService: ConfigService) {
        this.config = configService.getConfigSettings();

        console.log(this.config.WebApiBaseUrl);
    }
}

【讨论】:

  • 我无法将其标记为答案。我在工作的朋友说这是不可能的,并且只有一个 CI 定义来注入运行时变量。上传一个示例 Angular 项目让我将他展示为 PoC 会很棒。
  • 没问题,这里有一个 GIT:github.com/medeirosrich/ConfigExample 无论你是构建 dev 还是 prod,你都可以在 dist 文件夹中编辑 config.json 输出,设置将在运行时获取无论您选择部署。
  • 谢谢我在我的同事提到的时候附加了这个问题。他正在使用 Angular(2) 中的环境实践。尽管我已经提到他我们的网址是固定的,但他告诉我使用开箱即用的解决方案无法实现这一点,我们需要一个自定义的解决方案,而这个解决方案不是解决方案。如果能在更新后回复就好了。
  • 不幸的是,使用 angular-cli 的环境设置的当前实现无法立即完成您想要的操作。这正在这里积极讨论:github.com/angular/angular-cli/issues/3855。希望你想要的东西很快就会内置,否则在此期间你需要实现自定义工作。
  • Richard 据我了解,您提出的这个解决方案将帮助我们使用一个构建定义并添加/注入环境变量,对吗?
猜你喜欢
  • 2013-07-03
  • 1970-01-01
  • 1970-01-01
  • 2020-05-14
  • 2018-03-16
  • 1970-01-01
  • 2017-02-13
  • 2019-06-30
  • 1970-01-01
相关资源
最近更新 更多