如何在 angular 2 应用程序中添加 reCAPTCHA?

How to add reCAPTCHA in angular 2 application?

如何在您的 Angular 2 应用程序中集成 reCAPTCHA?

假设您有 reCAPTCHA 给定的 Site Key 和 Client Secret。将下面的代码放在组件中。

@ViewChild('captchaRef2') captchaRef2: ElementRef;
private _reCaptchaId: number;
private SITE_ID = [YourSiteKey];

ngAfterViewInit() {
    const grecaptcha = (window as any).grecaptcha;
    if (grecaptcha) {
      this._reCaptchaId = grecaptcha.render(this.captchaRef2.nativeElement, {
        'sitekey': this.SITE_ID,
        'callback': (resonse) => this.reCapchaSuccess(resonse),
        'expired-callback': () => this.reCapchaExpired()
      });
    }
}

下面是成功回调函数。如果响应数据有价值,则 reCAPTCHA 验证成功。

reCapchaSuccess(data:any){
    if(data){
      alert("Congratulation! reCAPTCHA verified.")
      // Some logic goes here
    }
  }

reCAPTCHA 过期时将调用以下函数。

reCapchaExpired(){
    alert("Oops! reCAPTCHA expired.")
    // Some logic goes here
  }

在 HTML 文件中放在 div 下方。

<div #captchaRef2></div>

将下面的 JS 脚本放在 index.html 文件中。

<script src='https://www.google.com/recaptcha/api.js?render=explicit" async defer'></script>

通过将js脚本放在上面,有时我会遇到以下错误: "grecaptcha.render is not a function" 所以,如果你遇到这个错误,只需使用下面的 js 脚本而不是上面的

<script src="https://www.google.com/recaptcha/api.js?render=explicit" async defer></script>

干杯!

如果 ng-recaptcha 存在,为什么要过于复杂?

  1. yarn add ng-recaptchanpm i ng-recaptcha --save

  2. 在您的模块之一中(例如 app.module.tsshared.module.ts 等)

(如解释here

import { RecaptchaModule, RECAPTCHA_SETTINGS, RecaptchaSettings } from 'ng-recaptcha';

@NgModule({
  imports: [RecaptchaModule],
  providers: [
    {
      provide: RECAPTCHA_SETTINGS,
      useValue: { siteKey: '<YOUR_KEY>' } as RecaptchaSettings,
    },
  ],
}) export class MyModule { }
  1. 在您的 html 中将其用作 <re-captcha>