Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/angular/33.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
如何在角度组件中使用javascript变量_Javascript_Angular - Fatal编程技术网

如何在角度组件中使用javascript变量

如何在角度组件中使用javascript变量,javascript,angular,Javascript,Angular,在我的.ts文件中有一些javascript代码(用于mapbox)用于角度组件。我希望在我的typescript代码中使用javascript代码中的变量(polygonCoordinates[]),但我不知道如何使用。我的代码中包含了ngOnInit()部分 我已经尝试过直接从javascript部分使用它,但没有成功。任何帮助将不胜感激,因为我是新手 ngOnInit() { let script = this.renderer2.createElement('script'

在我的.ts文件中有一些javascript代码(用于mapbox)用于角度组件。我希望在我的typescript代码中使用javascript代码中的变量(polygonCoordinates[]),但我不知道如何使用。我的代码中包含了ngOnInit()部分

我已经尝试过直接从javascript部分使用它,但没有成功。任何帮助将不胜感激,因为我是新手

  ngOnInit() {

    let script = this.renderer2.createElement('script');
    script.type = `application/javascript`;
    script.text = `
          var polygonCoordinates = [];   
          //and then there's some code for mapbox
        });
    `;
    this.renderer2.appendChild(this.document.body, script);

}

变量
polygonCoordinates
在全局范围内声明,可作为
窗口从任何位置访问。polygonCoordinates

var script=document.createElement('script');
script.type='application/javascript';
script.text=“var polygonCoordinates='hello';
document.head.appendChild(脚本);
//从任何地方

console.log(window.polygoncordinates)//您好
首先请参考变量的类型,如:
studentUpdateDetails:any=[]

然后像这样使用:
this.studentUpdateDetails=[{“key”:“value”},{“key”:“value”},{“key”:“value”},{“key”:“value”}]

为什么要在页面上附加脚本标记来创建变量/添加代码?为什么不直接执行代码呢?嗨,非常感谢你的回复。然而,console.log(window.polygonCoordinates)给了我这个错误消息:属性“polygonCoordinates”在类型“window&typeof globalThis”上不存在。这看起来像是typescript的编译时问题。试试看(任何一个窗口)。多学科协调学,我对它还不熟悉。非常感谢你。成功了!