0

In Angular my eval() is not working in the correct context.

I just want to test it with something simple like eval('console.log(this.sharedservice.var1)'); but says Cannot read property 'sharedservice' of undefined, so it doesn't know what this is.

When I try to do (0, eval)(script); which solves the this problem, then it says Cannot read property 'var1' of undefined. So know it doesn't know what sharedservice is. But in my component's constructor I do have private sharedservice: SharedService,. How can help eval see my component's constructor values?

Please don't suggest not to use eval, so tired of this argument.

Paul Kruger
  • 2,094
  • 7
  • 22
  • 49
  • 1
    Consider this the ["Obligatory don't use eval message"](https://stackoverflow.com/questions/197769/when-is-javascripts-eval-not-evil) – Liam Feb 19 '19 at 13:28

1 Answers1

0

You should not use eval. Is what you will hear from a lot of people. If you still want to use eval, you can try this:

export class BadIdea {
  constructor(private sharedservice: SharedService) {
    ((evalThis) => eval(evalThis)).call(this, 'console.log(this.lm.test)');
  }
}
Poul Kruijt
  • 69,713
  • 12
  • 145
  • 149