javascript - Importing script and calling a method on a variable
问题描述
I'm new to typescript and I'm trying to use a bit of code I found online to change links to look nice for my site,
<script src="https://wow.zamimg.com/widgets/power.js"></script>
<script>var wowhead_tooltips = {
"colorlinks": true,
"iconizelinks": true,
"renamelinks": true
};
</script>
I included that into my index.html, and it works great, until I load a component, I spent a lot of time looking around and found that I need to call $WowheadPower.refreshLinks();
To get the links to change when a new element is added, I wasn't sure how to declare that variable in typescript so I could tie it to various angular commands I wanted to do, unless I add it in a try catch:
loadScript(){
try{
// update tooltips
if(typeof $WowheadPower == 'undefined'){
$.getScript('//wow.zamimg.com/widgets/power.js');
} else {
$WowheadPower.refreshLinks();
console.log($WowheadPower)
}
} finally {}
}
I get an error that says Cannot find name '$WowheadPower' but I saved it anyway, and somehow on my page it works as I want it too.
It works perfect, but I still got the error so I declared it
try{
// update tooltips
var $WowheadPower
if(typeof $WowheadPower == 'undefined'){
$.getScript('//wow.zamimg.com/widgets/power.js');
} else {
$ WowheadPower.refreshLinks();
console.log($WowheadPower)
}
} finally {}
and it broke, I assume because I overwrote the correctly variable that has the right method.
Now I have to leave the error in to get functionality, but the error stops me from compiling when I ng serve. Until I hit save on VScode then it works fine again.
Any thoughts on how to resolve this?
解决方案
由于 $WowheadPower 是从另一个文件导入的外部变量,因此您可以告诉 typescript 它存在而不显式声明它:
declare var $WowheadPower: any
在代码的开头写下这个,这样你就可以告诉 TS 这个变量存在。理想情况下,您将编写一个正确定义$WowheadPower
' 类型而不是any
那里的接口。
推荐阅读
- python - 在 if 语句检查,Python 池上休眠线程
- python - Python cx_Oracle 绑定变量列表
- regex - 如何在 Visual Studio Code 正则表达式中查找和替换某些文本?
- javascript - 使用 push() 方法时如何避免二维数组中的重复?
- airflow - 将其他参数传递给 on_failure_callback
- c++ - Visual Studio 无法打开项目
- python - 我什么时候可以在 Django 中使用“请求”对象?
- tensorflow - 在数据集解析器函数中加载 NumPy 数组
- spring-cloud-sleuth - 使用 spring-cloud-sleuth 自定义跟踪日志
- python - 有没有办法制作元函数/元初始化器?