Home > Software design >  How to add a value with a dynamic property into config.json File
How to add a value with a dynamic property into config.json File

Time:10-04

When there is a value like this in the config.json file,

        {
           "timeout": 10000

        }

read the value as below in the implemented method in my .ts file

 duration :  this.config.getConfig('timeout')

My config.Service class is as,

  export class ConfigService {

  private config: Object = null;
  constructor(private http: HttpClient) { }

  public getConfig(key: any) {
    return this.config[key];
  }

  public loadConfig() {
    return this.http
      .get<Config>('../user/configuration/config.json')
      .toPromise()
      .then(Configdata => {
        this.config = Configdata;
      
      });
  }
}

And when there is a value like below in the implemented method in my .ts file in Angular.

errorMessage: "An error due to ${code} has been occured.Please try Again.Thanks!!!"

where 'code' is dynamic value.It varies depending on the scenario , I want to know whether we can add the errorMessage into config.json file or not?

If Possible,then how can I read it in the ts file after adding the errorMessage into config.json file?

Thankyou.

CodePudding user response:

A simplest way to do this is replace the code text with the dynamic values like this:

let errorText = "An error due to ${code} has been occured.Please try Again.Thanks!!!";
errorText = errorText.replace('${code}', 'pass the value');
console.log(errorText);

Add the errorMessage to the config file:

        {
           "timeout": 10000
           "errorMessage" : "An error due to ## has been occured.Please try Again.Thanks!!!"
        }
const errorText = this.config.getConfig('errorMessage').replace('##', 'the dynamic value');

  • Related