角度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文件中添加一个新的配置部分,但我没有想要这样做。
有没有办法做到这一点?
谢谢。
如果有人需要知道,请回答我自己的问题。
有四个步骤可以达到这个目的;-
第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'];
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句