Http 在 Angular 2 自定义异步验证中不起作用
Http doesn't work in Angular 2 custom asynchronous validation
我正在尝试创建一个自定义异步验证器,它会转到服务器并检查电子邮件是否已注册。
不幸的是,get 请求似乎从未被触发,因为什么也没有发生。我在 subscribe
中尝试了多个 console.logs,但他们没有 运行。
我检查过该请求是否在验证器之外工作,确实如此,所以这不是问题所在。
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;
}
}
这是因为您引用了函数并且丢失了 this
上下文。您可以使用 bind
方法或包装箭头函数来修复该问题(link 组件实例的函数):
this.signupForm = formBuilder.group({
'email': ['', Validators.required, this.checkEmail.bind(this) ],
});
或
this.signupForm = formBuilder.group({
'email': ['', Validators.required, (control:Control) => {
return this.checkEmail(control);
} ],
});
在您的情况下,this
不包含 http
属性...
我正在尝试创建一个自定义异步验证器,它会转到服务器并检查电子邮件是否已注册。
不幸的是,get 请求似乎从未被触发,因为什么也没有发生。我在 subscribe
中尝试了多个 console.logs,但他们没有 运行。
我检查过该请求是否在验证器之外工作,确实如此,所以这不是问题所在。
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;
}
}
这是因为您引用了函数并且丢失了 this
上下文。您可以使用 bind
方法或包装箭头函数来修复该问题(link 组件实例的函数):
this.signupForm = formBuilder.group({
'email': ['', Validators.required, this.checkEmail.bind(this) ],
});
或
this.signupForm = formBuilder.group({
'email': ['', Validators.required, (control:Control) => {
return this.checkEmail(control);
} ],
});
在您的情况下,this
不包含 http
属性...