xmaestro / angular2-recaptcha

Angular 2 : Typescript component for Google reCaptcha
ISC License
79 stars 30 forks source link

this.captcha.getResponse() returns null #43

Closed mareru closed 7 years ago

mareru commented 7 years ago

I have used this as a way to get methods from component:

import { Component, OnInit, ViewChild } from '@angular/core';

import {ReCaptchaComponent} from 'angular2-recaptcha/lib/captcha.component';

@Component({
    templateUrl: './login.component.html'
})
export class LoginComponent implements OnInit {
    @ViewChild(ReCaptchaComponent) captcha:ReCaptchaComponent;

    ngOnInit() {
    }

    private handleCorrectCaptcha(response: string) {
        let token = this.captcha.getResponse();
       console.log('reCAPTCHA response:');
       console.log(token);
    }

} 

But token ( this.captcha.getResponse()) returns null. What am I doing wrong? Must be something else to be configured in order for this to work?

mareru commented 7 years ago

I have found that the problem was here:

public getResponse(): String {

        if (!this.widgetId) // > change this to if(this.widgetId == null) // widgetId gets to be 0 (returned by google grecaptcha.render() function), so this is why it returned null 

            return null;

        //noinspection TypeScriptUnresolvedVariable

        return (<any>window).grecaptcha.getResponse(this.targetRef.nativeElement); // > pass here  this.widgetId instead of this.targetRef.nativeElement; otherwise we get error

    }
xmaestro commented 7 years ago

@mareru this commit should fix it.

mareru commented 7 years ago

Hi, @xmaestro, now I have different problem, I get this error:

Invalid ReCAPTCHA client id: [object HTMLDivElement]

It is solved when in getResponse() function, I mentioned in the previous post, this is done:

return (<any>window).grecaptcha.getResponse(this.targetRef.nativeElement); // > pass here this.widgetId instead of this.targetRef.nativeElement, error says it expects id, but gets div element

Also just a note, when your lib is downloaded in node_modules you have .idea files, I suppose those aren't supposed to be there, probably should be removed ...

xmaestro commented 7 years ago

Sorry i have been busy with other stuff, i'll correct this and check in..

xmaestro commented 7 years ago

Ok, It has been fixed.