I'm trying to create a custom asynchronous validator, that goes to the server and checks if an email is already registered.
Unfortunately, it seems that the get request is never fired, because nothing happens. I've tried multiple console.logs inside subscribe
, but they didn't run.
I've checked if that request works outside of the validator, and it does, so that's not the problem.
import { Component } from '@angular/core';
import { FormGroup, FormBuilder, Validators, FormControl } from '@angular/forms';
import { Response, Http } from '@angular/http';
@Component({
templateUrl: 'build/pages/welcome/signup/signup.html',
providers: [AuthService, CustomValidators]
})
export class Signup {
signupForm: FormGroup;
constructor(private formBuilder: FormBuilder, private http: Http) {
this.signupForm = formBuilder.group({
'email': ['', Validators.required, this.checkEmail],
}):
}
checkEmail(control: FormControl): Promise<any> {
const promise = new Promise<any>(
(resolve, reject) => {
this.http.get('/sharealead/main.php?action=checkEmail').subscribe(
(res: Response) => {
console.log('it never gets here');
console.log(res)
if (res.text() == 'already there') {
resolve({'emailTaken': true});
} else {
resolve(null);
}
},
(err) => {
console.log('it never gets here');
console.log(err);
}
)
}
);
return promise;
}
}
It's because you reference the function and you lose the
this
context. You can use thebind
method or a wrapping arrow function to fix that (link the function to the component instance):or
In your case,
this
doesn't contain anhttp
property...