【发布时间】:2017-06-01 14:01:27
【问题描述】:
在 Angular 2 中,我正在尝试创建自己的自定义验证器。
我创建了自己的 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 列为提供者,以便我的类接收该类的实例化对象。
“typeof CustomValidators”类型上不存在属性“api”
我是否以正确的方式提供课程?为什么方法不存在?
【问题讨论】:
-
我现在也遇到了同样的问题你找到解决办法了吗?
标签: angular dependency-injection dependencies custom-validators