私は非同期カスタム検証を実装しようとしていると私は角度2非同期カスタムバリデータ
export class CustomValidators{
_auth_service;
constructor(auth_service:AuthService){
this._auth_service = auth_service;
}
usernameTaken(control: Control) {
console.log(this._auth_service);
let q = new Promise<ValidationResult>((resolve, reject) => {
this._auth_service.emailtaken('email='+control.value).subscribe(data=>{
var result = data.json().result;
console.log(result);
if(result===true){
resolve({"usernameTaken": data});
}else{
resolve(null);
}
});
});
return q;
}
}
以下のようにそして、私のコンポーネント
this.customValidators = new CustomValidators(this._auth_service);
のIは、コントロールをフォームに追加して、検証のクラスを持っていますlike so
this.emailControl = new Control('',Validators.compose([Validators.required, Validators.pattern(ConfigService.EMAIL_REGEX)]),this.customValidators.usernameTaken);
私はバリデーターにサービスを注入しようとしているのが分かります。私のコンポーネントでバリデータ関数を使うためには、バリデータのオブジェクトを作成し、そのメソッドを使用しなければなりませんでした。私はthis._auth_service
プロパティが私のバリデータメソッドでundefined
と表示されるようにデバッグしました。それは私のバリデータのコンストラクタでうまく実装されているようです。
私は理解している指示文としてバリデーターを使いたくないので、簡単に注入することができます。
何が問題なのですか?
'this._auth_service'にコンストラクタの値がありますか? –
です。しかし、バリデータメソッドでは 'undefined'と表示されます – xmaestro
' this'は 'CustomValidators'のインスタンスではないので' undefined'です。 – dfsq