如何从 angular 应用程序中访问 Angular CLI 'ng start' 命令行变量

How to access Angular CLI 'ng start' command line variable from within angular app

Angular 11

我知道这个问题以前有人问过,但我找不到满意的答案。

在 angular CLI 我想 运行 命令

ng serve -o  --client=someclient

在 component.ts 文件或 service.ts 文件中我想访问客户端变量

if (client){
    this.loadClientConfig(client);
} else {
    this.loadClientConfig('whitelabel');
}

loadClientConfig(c){
    // go load the client config section from a config.json file if it exists (this bit i know how to do)
}

我知道这可以通过添加 --configuration=someClient 完成,但据我所知,我需要向 [=35= 添加一个新的配置部分] 文件和一个新的 environment.ts 文件,我不想这样做。

有办法吗?

谢谢。

回答我自己的问题以防其他人需要知道。

实现这个有4个步骤;-

第 1 步。add/edit package.json 中的脚本(这里的示例是 ng serve 但可以是构建等)

"start":"node set-tenant.js --tenant=somevalue && ng serve -o" 

步骤 2. 在根目录中创建 set-tenant.js 文件

console.info('Attempting to set  "tenant" variable in index.html');
let tenant = null;
const indexHtml = 'src/index.html';
process.argv.forEach(a => {
  if (a.startsWith('--tenant')){
    tenant = a.split('=')[1];
  }
});
const fs = require('fs')
fs.readFile( indexHtml, 'utf8', function (err, data) {
  if (err){ return console.error(err); }
  if (data.length){
    console.info('Setting  "tenant" variable in index.html to ' + tenant);
    const matchRule = /\/\*tenant-start\*\/.*\/\*tenant-end\*\//g;
    fs.writeFile( indexHtml, data.replace( matchRule, `/*tenant-start*/window['tenantId'] = '${tenant}';/*tenant-end*/`), 'utf8', function (err) {
        if (err) return console.error(err);
    });
  } else {
    return console.error(indexHtml + ' has no content');
  }
});

步骤 3. 将代码添加到 index.html 文件

<script>/*tenant-start*/window['tenantId'] = 'gtr';/*tenant-end*/</script>

步骤 4. 在您​​的 TS 组件和服务文件中访问租户变量

// tslint:disable-next-line: no-string-literal
this.tenant = window['tenantId'];