Http在Angular 2自定义异步验证中不起作用 [英] Http doesn't work in Angular 2 custom asynchronous validation

查看:104
本文介绍了Http在Angular 2自定义异步验证中不起作用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试创建一个自定义的异步验证器,该验证器将转到服务器并检查是否已注册电子邮件.

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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆