Reputation: 900
I made a reactive form when a user filled a field and hit submit it will redirect to a page. Now, after that, I will trigger
this.router.navigate['somepage']
All's working until I've implemented reCAPTHCA v2 in my reactive form.
Here's my simple reactive form setup:
<form [formGroup]="searchForm" (ngSubmit)="onSearchSubmit()">
....
<div id="recaptcha" data-sitekey="xxx" class="g-recaptcha"></div>
<button type="submit" [disabled]="flag">search</button>
</form>
<script src="https://www.google.com/recaptcha/api.js?onload=onloadCallback&render=explicit"
async defer>
Then again, all's working up to this point even on the insertion of the script tag, the callback onloadCallback
is called up to the verification/validation if a user is a bot or not.
Pretty much the reactive form + reCAPTCHA works BUT the router seemed to be clogged or blocked.
Router links binded to the anchors works, the routerLinkActive properly set the style class accordingly yet components are not rendered.
I've trimmed it down to this:
I can't use any kind of navigation using router WHEN router is called in the scope of the reCAPTCHA's intialization and verification functions as shown below.
declare var grecaptcha : any;
@Component({
...
})
export class TestComponent {
//
testSubObs: Subject < any > = new Subject();
constructor(...) {}
ngOnInit() {
// ....
this.testSubObs.subscribe(
e => {
//router still doesnt work here
this.router.navigate(['/somepage']);
});
setTimeout(() => {
this.router.navigate(['/somepage']); //works
}, 5000);
}
initCaptcha() {
const verify = (response) => {
// works
console.log(response);
// doesnt work
this.router.navigate(['/stack']);
this.testSubObs.next(response);
}
this.windowService.nativeWindow.onloadCallback = () => {
// this works, properly renders the widgets
grecaptcha.render('recaptch', {
'sitekey': xxxx,
'callback': verify // tried verify.bind(this) still doesnt work. this is inside an arrow function. It doesnt matter in the first place.
})
// doesnt work
this.router.navigate(['/stack']);
}
//this works
this.router.navigate(['/stack']);
}
}
I tried using observables in those functions to call the router outside those functions, still it doesn't work. Did I miss out anything? Please help. Thanks.
In addition, I placed a <a [routerLink]="..">
in the HTML template in the same component and the routing properly works. This confuses me a lot for there's no error appearing, I've even tried aot
still no errors or even warnings appear.
Upvotes: 2
Views: 870
Reputation: 1931
Try to trigger your route's navigation inside "NgZone" :
import { component, NgZone } from '@Angular/core';
.....
custructor(private zone : NgZone, private router : Router) {}
.....
this.zone.run (() => {
this.router.navigate(['/stack']);
})
Upvotes: 1