Search code examples
angularevalenvironment

angular and eval: i get an error with environment


I do this:

let var1="environment.test";
console.log(eval(var1));

I get the error: ERROR ReferenceError: environment is not defined

If i do console.log(environment.test); it works

If i do

let var1="var2";
let var2="myvalue";
console.log(var1);
console.log(eval(var1));
it works. The problem is 'environment'. How can I do? Thx a lot


Solution

  • You should avoid using eval. See this link.

    However to use it once you import environment like this:

    import { environment } from '../environments/environment';
    

    You can use it with eval like this:

    export class AppComponent {
    
      environment = environment;
    
      constructor() {
        console.log('prefered way:', environment.test); // <-- use this instead
        let var1 = "this.environment.test";
        console.log(eval(var1));
      }