文章内容
2020/6/13 9:06:10,作 者: 黄兵
Angular比较好用的google reCAPTCHA包
最近Angular项目上需要使用google reCAPTCHA包,但是测试了好几个,总是或多或少存在一些问题。
经过测试:ng-recaptcha,这个包。虽然也存在一些问题,但是还是经过修改把问题解决了。
同时文档写的也很清晰,同时存在一些不错的Demo。
正文开始:
首先是两个不错的在线Demo,可以看看:
1、ng-recaptcha Stackblitz demo
2、Configuring the component globally
存在的一些问题:
首先是google reCAPTCHA相关配置问题:
{
provide: RECAPTCHA_V3_SITE_KEY,
useValue: environment.googleRecaptchaKeyV3,
},
{
provide: RECAPTCHA_BASE_URL,
useValue: 'https://recaptcha.net/recaptcha/api.js', // use recaptcha.net script source for some of our users
},
官方使用的是直接写死再app.module,在项目事件中,会导致上线了需要修改配置,非常麻烦,这里直接通关环境配置,来加载不同的key,具体可以参考这篇文章:Angular中的环境变量。
第二个问题是后天自动提交问题,官方文档是这么写的:
import { OnExecuteData, ReCaptchaV3Service } from 'ng-recaptcha'; @Component({ selector: 'my-component', templateUrl: './v3-demo.component.html', }) export class MyComponent implements OnInit, OnDestroy { private subscription: Subscription; constructor( private recaptchaV3Service: ReCaptchaV3Service, ) { } public ngOnInit() { this.subscription = this.recaptchaV3Service.onExecute .subscribe((data: OnExecuteData) => { this.handleRecaptchaExecute(data.action, data.token); }); } public ngOnDestroy() { if (this.subscription) { this.subscription.unsubscribe(); } } }
但是经过测试,好像并不会执行,不知道是什么问题。
但是经过修改:
ngAfterViewInit() {
this.sub = this.recaptchaV3Service.execute('home')
.subscribe((token) => {
this._reCAPTCHA.reCAPTCHAPost(token).subscribe(res => {
console.log(token);
console.log(res);
}, (error: any) => {
console.log(error + 'recaptchaV3Service');
this.errorMessages.push({description: 'Server error. Try later.'});
this._logService.error(error, `path: ${this.uri}`, 'function: setMate()');
});
});
}
已经可以正常运行。
在项目中google reCAPTCHA v2、v3都经过测试,未出现什么问题。
评论列表