Ale*_*fan 7 asynchronous angular2-forms angular
我正在尝试创建一个自定义异步验证器,它将转到服务器并检查电子邮件是否已注册.
不幸的是,似乎get请求永远不会被触发,因为没有任何反应.我在里面尝试了多个console.logs subscribe,但是他们没有运行.
我已经检查过该请求是否在验证器之外工作,而且确实如此,所以这不是问题所在.
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;
}
}
Run Code Online (Sandbox Code Playgroud)
这是因为你引用了这个函数而你失去了this上下文.您可以使用bind方法或包装箭头函数来修复它(将函数链接到组件实例):
this.signupForm = formBuilder.group({
'email': ['', Validators.required, this.checkEmail.bind(this) ],
});
Run Code Online (Sandbox Code Playgroud)
要么
this.signupForm = formBuilder.group({
'email': ['', Validators.required, (control:Control) => {
return this.checkEmail(control);
} ],
});
Run Code Online (Sandbox Code Playgroud)
在您的情况下,this不包含http属性...
| 归档时间: |
|
| 查看次数: |
2915 次 |
| 最近记录: |