我正在使用Ionic2框架构建应用程序。我有一个表格要求用户提供电子邮件地址。我为该表单构建了一个自定义异步验证器,它访问我的API端点以检查给定的电子邮件地址是否已被使用。
import {FormControl} from '@angular/forms';
import {Http} from "@angular/http";
import {Injectable} from "@angular/core";
@Injectable()
export class SignUpValidator {
constructor(private http: Http) {
}
validateEmail(control: FormControl): any {
console.log("this, in validateEmail: " + this);
return new Promise((resolve, reject) => {
this.http.post('localhost:3000/api/registration/checkemail', {email: control.value})
.map(res => res.json())
.subscribe(
data => {
if (data.emailInUse) {
resolve({
"email in use": true
});
}
else {
resolve(null);
}
},
error => {
console.log(error);
reject(error);
}
);
});
}
}
验证运行时我收到以下错误:
EXCEPTION: Cannot read property 'http' of undefined
显然,'这个'未定义,但我想知道原因。当我只是导航到我的表单所在的页面时,似乎在用户甚至将任何信息输入表单之前调用验证器函数三次。还有什么,'这个'在我的验证器的前两次调用中定义,但在第三次和后续调用中未定义。
一旦页面导航到,控制台输出就像这样:
this, in validateEmail: [object Object] sign-up.validator.ts:49
this, in validateEmail: [object Object] sign-up.validator.ts:49
this, in validateEmail: undefined sign-up.validator.ts:49
调用此验证程序的Component如下所示:
import {Component, ViewChild} from '@angular/core';
import {NavController, Slides, ToastController, Checkbox, App} from 'ionic-angular';
import {FormBuilder, Validators, FormGroup} from "@angular/forms";
import {SignUpValidator} from "./sign-up.validator";
import {AuthService} from "../../services/auth.service";
import {AccountCreationService} from "../../services/account-creation.service";
@Component({
selector: 'page-sign-up',
templateUrl: 'sign-up.html',
providers: [AuthService, AccountCreationService, SignUpValidator]
})
export class SignUpPage {
@ViewChild('signupSlider') slider: Slides;
@ViewChild('individual') individual: Checkbox;
@ViewChild('business') business: Checkbox;
private formPersonalInformation: FormGroup;
private formLoginInformation: FormGroup;
private formCreditCardInformation: FormGroup;
private checkboxPro: string;
private checkboxConsumer: string;
private businessType: string;
private fullName: string;
private DOB: string;
private addressLine1: string;
private addressLine2: string;
private state: string;
private city: string;
private zipCode: number;
private country: string;
private email: string;
private password1: string;
private password2: string;
constructor(public navCtrl: NavController, private authService: AuthService,
public formBuilder: FormBuilder, private toastCtrl: ToastController,
private app: App, private accountCreationService: AccountCreationService,
private signUpValidator: SignUpValidator) {
this.formLoginInformation = formBuilder.group({
email: ['', Validators.compose([Validators.maxLength(45), Validators.pattern('[A-z0-9._%+-]+@[A-z0-9.-]+\.[A-z]{2,}')]), signUpValidator.validateEmail],
password1: ['', Validators.required],
password2: ['', Validators.required],
checkboxPro: [null],
checkboxConsumer: [null]
});
...
为什么在表单被触及之前我的验证器被调用了三次,为什么'这个'消失?