angular - 如何从 Angular 应用程序中访问 Angular CLI 'ng start' 命令行变量
问题描述
角 11
我知道以前有人问过这个问题,但我找不到满意的答案。
在角度 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来完成,但据我所知,我需要在 angular.json 文件中添加一个新的配置部分,并为每个客户端添加一个新的 environment.ts 文件,但我不需要想要这样做。
有没有办法做到这一点?
谢谢你。
解决方案
回答我自己的问题,以防其他人需要知道。
有 4 个步骤可以实现这一目标;-
步骤 1. 在 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'];
推荐阅读
- javascript - 使用 HERE MAPS API 从数据库导入标记
- python - 如何检查某些东西是否存在,然后创建并将其保存在数组中
- python - sklearn 中的 GridSearchCV 和 Pipeline 是否存在拟合差异?
- scala - 如何在 Spark scala 中优化 withColumn?
- ios - iOS:连接到 BLE 设备时是否总是显示配对窗口?
- vue.js - nuxt架构中的模态窗口
- python - 使用 url 模式 Django 从 ListView 中的函数直接恢复变量
- javascript - 在统一 3d 的创建选项中没有创建 javascript 的选项。仅显示 c# 脚本
- python - 如何将模块中的一些函数和类导入测试文件?
- c++ - 尽可能在编译时强制执行函数契约