将外部js文件添加到组件中。该文件在Angular中的调用函数

时间:2019-03-30 04:31:03

标签: angular

我正在尝试将此JavaScript文件添加到我的组件中:

https://cdn.firstpromoter.com/fprom.js

已向我提供了以下功能以添加到我的组件中:

          $FPROM.trackSignup({
            email:this.userEmail,
            uid:this.userId
          },
          function(){
          });

添加该功能时,出现控制台错误:

ERROR in mypath/component.ts: error TS2304: Cannot find name '$FPROM'.

该外部JavaScript文件中似乎存在$FPROM,但控制台没有拾取它。

到目前为止,我所做的工作是创建自己的JavaScript文件,将JavaScript代码复制到其中,然后将该文件放置在我的组件文件夹中,然后将其导入顶部,如下所示:

import './fprom.js';

和我的组件中的上述功能

我知道我做错了,因为遇到控制台错误。我该如何解决这个问题?

1 个答案:

答案 0 :(得分:1)

用于加载Google reCaptcha的示例指令,这也是一个外部js文件。您可以实施类似的方法来加载js文件。

看看以下方法:

  1. addScript()->加载外部脚本
  2. registerReCaptchaCallback()->在脚本加载后使用全局变量。
export class ReCaptchaDirective implements OnInit, ControlValueAccessor {
  @Input() key: string;
  @Input() config: ReCaptchaConfig = {};
  @Input() lang: string;

  @Output() captchaResponse = new EventEmitter<string>();
  @Output() captchaExpired = new EventEmitter();

  private widgetId: number;

  private onChange: (value: string) => void;
  private onTouched: (value: string) => void;

  constructor(
    private element: ElementRef,
    private ngZone: NgZone
  ) {}

  ngOnInit() {
    this.registerReCaptchaCallback();
    this.addScript();
  }

// accessing the `recaptcha` var loaded in global scope.
  registerReCaptchaCallback() {
    // @ts-ignore
    window.reCaptchaLoad = () => {
      const config = {
        ...this.config,
        sitekey: this.key,
        callback: this.onSuccess,
        'expired-callback': this.onExpired
      };
      this.widgetId = this.render(this.element.nativeElement, config);
    };
  }

// method to load the external js file and add to dom
  addScript() {
    const script = document.createElement('script');
    const lang = this.lang ? '&hl=' + this.lang : '';
    script.src = `https://www.google.com/recaptcha/api.js?onload=reCaptchaLoad&render=explicit${lang}`;
    script.async = true;
    script.defer = true;
    document.body.appendChild(script);
  }

 ... //other captcha handler methods and code

  private render(element: HTMLElement, config): number {
    // @ts-ignore
    return grecaptcha.render(element, config);
  }
}

注意:为避免出现棉绒错误,请避免使用//@ts-ignore。您也可以定义一个简单类型。

相关问题