Forms 如何在angular 2 final中的异步表单验证方法中进行http调用?

Forms 如何在angular 2 final中的异步表单验证方法中进行http调用?,forms,validation,http,angular,asynchronous,Forms,Validation,Http,Angular,Asynchronous,我正在使用Angular 2最终版本,并尝试进行异步表单验证。在我的组件中,构造函数中有以下代码: this.myForm = this._formBuilder.group({ 'firstName': ['', Validators.compose([Validators.required, Validators.maxLength(45), ValidationService.nameValidator])], 'userName': ['', Valida

我正在使用Angular 2最终版本,并尝试进行异步表单验证。在我的组件中,构造函数中有以下代码:

this.myForm = this._formBuilder.group({
        'firstName': ['', Validators.compose([Validators.required, Validators.maxLength(45), ValidationService.nameValidator])],
        'userName': ['', Validators.compose([Validators.required]), Validators.composeAsync([ValidationService.userNameValidator])],
        'userEmail': ['', Validators.compose([Validators.required, ValidationService.emailValidator])],
        'confirmEmail': ['', Validators.required],
        'password': ['', Validators.compose([Validators.required, ValidationService.passwordValidator])],
        'confirmPassword': ['', Validators.required]
        });
我试图通过http调用检查数据库中是否已经存在输入的用户名

验证方法如下:

static userNameValidator(control: FormControl){
    let http: Http;
    if ( control.value.trim().length === 0 ) {
        return new Promise((resolve, reject) => {
            resolve(null);
        });
    }
    if (control.value) {
        console.log('value:' + control.value);
        return new Promise((resolve, reject) => {
            setTimeout(() => {
                var url = '/isUserNameUnique/';//this is getting printed
                console.log('url is ' + url);
                http.get(url + control.value + '/').map(response => response.json()).subscribe(result => {
                    if (result === false) {
                        resolve({'userAlreadyInUse': true});
                    } else {
                        resolve(null);
                    }
                });
            }, 1000);
        });
    }
}
控制台正在打印。但没有进行http调用。错误说

TypeError: Cannot read property 'get' of undefined

有人能帮我理解到底是什么问题吗?

你没有使用http
dependency。我要说的是用静态方法定义类。然后在构造函数中请求
http
依赖项,并在任何需要的地方使用它

代码

@Injectable()
export class MyClass {
  constructor(private http: Http) {}
  static userNameValidator(control: FormControl) {
    if (control.value.trim().length === 0) {
      return new Promise((resolve, reject) => {
        resolve(null);
      });
    }
    if (control.value) {
      console.log('value:' + control.value);
      return new Promise((resolve, reject) => {
        setTimeout(() => {
          var url = '/isUserNameUnique/'; //this is getting printed
          console.log('url is ' + url);
          //used http as this.http 
          this.http.get(url + control.value + '/').map(response => response.json())
          .subscribe(result => {
            if (result === false) {
              resolve({
                'userAlreadyInUse': true
              });
            } else {
              resolve(null);
            }
          });
        }, 1000);
      });
    }
  }
}

您没有通过从Dependency获取http来使用它。我要说的是用静态方法定义类。然后在构造函数中请求
http
依赖项,并在任何需要的地方使用它

代码

@Injectable()
export class MyClass {
  constructor(private http: Http) {}
  static userNameValidator(control: FormControl) {
    if (control.value.trim().length === 0) {
      return new Promise((resolve, reject) => {
        resolve(null);
      });
    }
    if (control.value) {
      console.log('value:' + control.value);
      return new Promise((resolve, reject) => {
        setTimeout(() => {
          var url = '/isUserNameUnique/'; //this is getting printed
          console.log('url is ' + url);
          //used http as this.http 
          this.http.get(url + control.value + '/').map(response => response.json())
          .subscribe(result => {
            if (result === false) {
              resolve({
                'userAlreadyInUse': true
              });
            } else {
              resolve(null);
            }
          });
        }, 1000);
      });
    }
  }
}

我使用的方法与您最初给出的方法类似,比如在构造函数中使用http,然后在静态方法中使用它,如下所示。这是不允许的。所以我把MyClass.http放在这里。错误并不存在。但同样的错误,如“TypeError:无法读取未定义的”属性“get”。@revati在使用
MyClass
之前,必须使其
@Injectable
&将静态方法导入任何需要的地方。然后用它。是的,我已经用过了。我的类用'@Injectable'注释,因为它是一个服务,并且该服务正在组件上导入。服务和组件也在app.module.ts的声明和提供者数组中声明。仍然没有跳跃。@Revati我能不能请你创建一个小的弹跳器,这样我就可以玩它了。很抱歉回复延迟。问题解决了。我所做的是使方法非静态。然后,我将http依赖项放在构造函数中。然后我改变了-->>>“用户名”:[“”,Validators.compose([Validators.required]),Validators.composeSync([this.\u validationService.usernamevidator.bind(this.\u validationService)])我使用了您最初给出的方法,比如在构造函数中使用http,然后在静态方法中使用它。这是不允许的。所以我把MyClass.http放在这里。错误并不存在。但同样的错误,如“TypeError:无法读取未定义的”属性“get”。@revati在使用
MyClass
之前,必须使其
@Injectable
&将静态方法导入任何需要的地方。然后用它。是的,我已经用过了。我的类用'@Injectable'注释,因为它是一个服务,并且该服务正在组件上导入。服务和组件也在app.module.ts的声明和提供者数组中声明。仍然没有跳跃。@Revati我能不能请你创建一个小的弹跳器,这样我就可以玩它了。很抱歉回复延迟。问题解决了。我所做的是使方法非静态。然后,我将http依赖项放在构造函数中。然后我更改为-->>>>'userName':['',Validators.compose([Validators.required]),Validators.composeSync([this.\u validationService.userNameValidator.bind(this.\u validationService)])]