首页 > 解决方案 > ng-recaptcha 标签路由更改时导致错误“zone.js:未处理的承诺拒绝”

问题描述

我在 Angular 组件上使用“ng-recaptcha”。我在这样的表格中使用:

<form class="form-contact"
        [formGroup]="contactForm"
        #formDirective="ngForm" 
        (ngSubmit)="sendMessage(contactForm, formDirective)">
  <re-captcha class="recaptcha"
              formControlName="captcha"
              siteKey="mysitekey">
  </re-captcha>
</form>

然后我将表单发送到组件:

export class AboutComponent implements OnInit, OnDestroy {
  contactForm: FormGroup;
  captchaResponse: string;
  private emailSubscription: Subscription;

  constructor(private emailService: EmailService) { }

  ngOnInit() {
    this.contactForm = new FormGroup({
      captcha: new FormControl('', Validators.required)
    });
  }
  
  ngOnDestroy(): void { 
    if (this.emailSubscription) { this.emailSubscription.unsubscribe(); } 
  }

  sendMessage(contactForm: FormGroup, formDirective: FormGroupDirective) {
    if (contactForm.valid) {
      this.emailSubscription = this.emailService.sendEmail(contactForm.value)
        .subscribe((response: ApiResponse) => {
          if (response.success) {
            console.log(response.message);
            formDirective.resetForm();
            contactForm.reset();
          } else {
            this.alertService.error(response.message);
          }
        }, (error: HttpErrorResponse) => {
          console.log({status: error.status, error: error.error});
          this.alertService.error('Error sending message. Please try again later or send a direct message.');
        }
      );
    }
  }
}

一切似乎都运行良好。但是,当路由更改(例如用户转到另一个页面)并AboutComponent再次呈现时,会弹出一个错误:Unhandled Promise rejection: timeout ; Zone: <root> ; Task: Promise.then ; Value: timeout undefined. 我 99% 确定这是由<re-captcha>标签引起的,因为删除标签后错误不会出现。有没有办法在路由更改时呈现验证码而不会出错(并且在我回到组件后重新加载验证码)?

链接到 Stackblitz:stackblitz

标签: htmlangulartypescriptrecaptcha

解决方案


这是一个临时且非常糟糕的修复,但它对我有用

 // somewhere in your "main.ts" or "app.component.ts"
import { RecaptchaComponent } from 'ng-recaptcha';
RecaptchaComponent.prototype.ngOnDestroy = function() {
  if (this.subscription) {
    this.subscription.unsubscribe();
  }
}

阅读更多:https ://github.com/DethAriel/ng-recaptcha/issues/123#issuecomment-426112101


推荐阅读