0

Angular 11

I know that this question has been asked before but I can find no satisfactory answer.

In angular Cli I want to run the command

ng serve -o  --client=someclient

within an component.ts file or a service.ts file I want to access the client variable thus

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)
}

I know this can be done by adding --configuration=someClient but as far as I can tell I then need to add a new configuration section to the angular.json file and a new environment.ts file for every client and I don't want to have to do that.

is there a way to do this?

thank you.

1 Answer 1

1

Answering my own question in case anyone else needs to know.

There are 4 steps to achieve this;-

Step 1. add/edit script in package.json (example here is ng serve but can be a build etc)

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

Step 2. create set-tenant.js file in the root

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');
  }
});

Step 3. add code to index.html file

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

Step 4. access the tenant variable in your TS component and service files

// tslint:disable-next-line: no-string-literal
this.tenant = window['tenantId'];
Sign up to request clarification or add additional context in comments.

1 Comment

this post shows how to add variables into angular code, and that helps me a lot, thank you! I also refer this post stackoverflow.com/a/66671453/560773 that use js file system module to generate ts with variables automatically, you may want to check it out

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.