Http doesn't work in Angular 2 custom asynchro

2019-02-13 09:00发布

I'm trying to create a custom asynchronous validator, that goes to the server and checks if an email is already registered.

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;
     }

}

1条回答
我想做一个坏孩纸
2楼-- · 2019-02-13 10:01

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) ],
});

or

this.signupForm = formBuilder.group({
         'email': ['', Validators.required, (control:Control) => {
           return this.checkEmail(control);
         } ],
});

In your case, this doesn't contain an http property...

查看更多
登录 后发表回答