如何将变量从打字稿传递到嵌入式JS?

时间:2020-03-09 14:34:09

标签: javascript angular typescript

我遇到的一种情况是我在我的角度项目中使用JavaScript,但无法使用变量来具有动态行为,有没有办法我可以使用 this.testID ,这是我从服务处收到的,然后将其传递给下面的JS代码,该代码中我当前的静态值为 1234 。请让我知道您的建议/解决方案。

public ngOnInit() {
    this.testID = this.someSettings.testID; // this is the ID to be passed to below JS 
  }

  public onClicked() {
    let script = this._renderer2.createElement('script');
    script.type = `text/javascript`;
    script.text = `{          
      window._fs = window._fs || [];
      _fs.push(['cid', 'something']);
      _fs.push(['uid', '1234']); // here is where I want the ID from above to be passed instead of 1234
    }`;
    this._renderer2.appendChild(this._document.body, script);
  }

谢谢

1 个答案:

答案 0 :(得分:0)

您的整个script.text位于反引号中,即一种支持多行和解释值的字符串:

script.text = `{  // <--- Starting backtick        
      window._fs = window._fs || [];
      _fs.push(['cid', 'something']);
      _fs.push(['uid', ${this.testID}]); //  <-- Interpreted value
}`;  // <--- Ending backtick