【问题标题】:Add external js file into component. call function inside that file in Angular将外部 js 文件添加到组件中。在 Angular 中调用该文件中的函数
【发布时间】:2019-08-21 00:40:54
【问题描述】:

我正在尝试将此 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'.

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

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

import './fprom.js';

在我的组件中,放入上面的函数

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

【问题讨论】:

  • 您应该创建一个自定义指令来加载文件并检查$FPROM var 在window 范围内是否可用。一旦可用,您就可以调用上面发布的方法。

标签: angular


【解决方案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);
  }
}

注意:避免在出现 lint 错误时使用 //@ts-ignore。你也可以定义一个简单的类型。

【讨论】:

    猜你喜欢
    • 2018-12-21
    • 2020-10-19
    • 2018-12-16
    • 2020-12-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多