Http在Angular 2自定义异步验证中不起作用 [英] Http doesn't work in Angular 2 custom asynchronous validation
问题描述
我正在尝试创建一个自定义的异步验证器,该验证器将转到服务器并检查是否已注册电子邮件.
I'm trying to create a custom asynchronous validator, that goes to the server and checks if an email is already registered.
不幸的是,似乎没有触发get请求,因为什么也没发生.我已经在subscribe
中尝试了多个console.logs,但是它们没有运行.
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;
}
}
推荐答案
这是因为您引用了该函数,并且失去了this
上下文.您可以使用bind
方法或环绕箭头函数来修复该问题(将该函数链接到组件实例):
It's because you reference the function and you lose the this
context. You can use the bind
method or a wrapping arrow function to fix that (link the function to the component instance):
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
属性...
In your case, this
doesn't contain an http
property...
这篇关于Http在Angular 2自定义异步验证中不起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!