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

查看:27
本文介绍了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天全站免登陆