我在组件上有一个Recaptcha,但是如果我使用路由器通过Recaptcha导航到该组件,则每次导航回该组件时,Recaptcha都不再存在。
在组件ts文件中:
import { Component, OnInit, ViewChild, ElementRef } from '@angular/core';
import { Router } from '@angular/router';
declare var grecaptcha: any;
@Component({
selector: 'app-index',
templateUrl: './index.component.html',
styleUrls: ['./index.component.css']
})
export class IndexComponent implements OnInit {
constructor(private _router: Router) { }
@ViewChild('captcha') captcha:ElementRef;
renderCaptcha(){
grecaptcha.render(this.captcha.nativeElement, {
callback: (e) => this.captchaCallback(e)
});
}
captchaCallback(code:string){
console.log('got result', code);
}
ngOnInit() {
if('grecaptcha' in window){
this.renderCaptcha();
} else {
window['loaded'] = () => {
console.log('loaded');
this.renderCaptcha();
}
};
}
}
组件html
<div id="g-recaptcha" data-callback="resolve" data-sitekey="6LeIxAcTAAAAAJcZVRqyHh71UMIEGNQ_MXjiZKhI"></div>
脚本标签
<script src="https://www.google.com/recaptcha/api.js?onload=loaded&render=explicit" async defer></script>
我要达到什么目的?我希望每次加载该组件时都重新加载验证码。