编译期间如何使Angular ignor错误

问题描述

我有一个函数,可用于将数据传递到javascript中的API。该函数使用我放在html页面标题中的API javascript链接

现在我正在使用Angular重建整个系统,该功能标记错误,并且我无法使用“ ng build --prod”来构建项目。无论如何,我可以使编译器知道该函数来自放置在index.html页面中的API链接,还是可以使编译器忽略该错误并构建项目。这是与api链接连接的函数“ getPaidSetup()”。

....
....

  doSomething(){
      // the following getpaidSetup() function is throwing an error "error TS2304: Cannot find name 'getpaidSetup'."
      var x = getpaidSetup({ // this is dependent on the link placed in the index page
          customer_email: 'useremailishere@domain.com',amount: 1000,});
  }
 ----

Anyone with idea on how I can build the project or make the compiler ignore the error? Thanks in advance

解决方法

这是@Vikas建议的有助于OP退出的注释的解释,该注释将尝试(window as any)以调用在index.html上定义的函数。评论太久了,基本上解决了OP的需求。

答案是1)命名空间和2)打字稿

如果您位于全局名称空间中,并且定义了一个函数,则它将成为window的属性。在这种全局背景下,您不必明确说出window.getPaidSetup(),而可以说`getPaidSetup()。

在Angular中,几乎总是在“类”中定义函数,“类”是它自己的名称空间。如果您想在window上进行呼叫,则需要明确地说出来。 window.getPaidSetup()

但是,我们使用的是打字稿,如果您说window.getPaidSetup()(尝试一下),它应该会抱怨。为什么?因为打字稿不知道您用新函数扩展了窗口对象类型。使其安静的一种快速而肮脏的方法是将其强制转换为any,这意味着不必担心严格的类型。您可以使用(window as any).getPaidSetup()进行投射。

这是一篇不错的博客文章,我发现它比您想知道的更多! https://mariusschulz.com/blog/declaring-global-variables-in-typescript