2

在Angular 2中我试图创建自己的自定义验证器。Angular2自定义验证器与依赖关系

我已经创建了我自己的CustomValidators类,它实现了验证器接口。

import { FormControl } from "@angular/forms"; 
import { MyhttpService } from "./myhttp.service"; 
import { Response } from "@angular/http"; 
import { Injectable, Directive } from '@angular/core'; 


@Injectable() 
export class CustomValidators{ 

constructor(private _http : MyhttpService){ 

} 

public api(c : FormControl) 
{ 
    // Run 
    this._http.get("/expenses/email?email=" + c.value).subscribe((res:Response) => { 
     if(res.status === 200){ 
      // email exists 
      return null; 
     } else { 
      return {"email" : true} 
     } 
    }); 
} 

如果我使api成为静态方法,那么我可以成功地使用这个类。

this._formDetails = fb.group({ 
    "managerEmail" : ["", [Validators.required, CustomValidators.api] ] 
}); 

但是,当然这是一个静态方法,所以我没有权限访问任何构造函数值,因为构造函数尚未运行。

因此我无法找到一种实现具有依赖项的自定义验证器的方法,必须有一种方法。

我已经尝试列出CustomValidators作为提供程序,所以我的类接收该类的实例化对象。

属性“API”的类型不存在“的typeof CustomValidators”

上午我提供正确的方式类?为什么该方法不存在?

+0

我现在有同样的问题,你现在找到了解决方案吗? –

回答

0

试试这个:

this._formDetails = fb.group({ 
    "managerEmail" : ["", Validators.required, CustomValidators.api] 
}); 

Validators.required是同步验证,但你的CustomValidators.api是一个异步验证。

根据the official documentation,每个表单控件应该指定状态,同步验证程序,然后是异步验证程序。

+0

你的答案中包含一个错误: 'this._formDetails = fb.group({ “managerEmail”: “”,Validators.required],[CustomValidators.api] });' 是你的意思。但这不是他的问题的答案。 –