2016-04-20 23 views
2

私は非同期カスタム検証を実装しようとしていると私は角度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と表示されるようにデバッグしました。それは私のバリデータのコンストラクタでうまく実装されているようです。

私は理解している指示文としてバリデーターを使いたくないので、簡単に注入することができます。

何が問題なのですか?

+0

'this._auth_service'にコンストラクタの値がありますか? –

+0

です。しかし、バリデータメソッドでは 'undefined'と表示されます – xmaestro

+0

' this'は 'CustomValidators'のインスタンスではないので' undefined'です。 – dfsq

答えて

6

あなたが文脈を失っているように見えます。バリデータメソッドをバリデータインスタンスオブジェクトに明示的にバインドする必要があります。

this.emailControl = new Control('', Validators.compose([ 
    Validators.required, 
    Validators.pattern(ConfigService.EMAIL_REGEX) 
]), this.customValidators.usernameTaken.bind(this.customValidators)); 
+0

この場合、 '.bind()'が何をしているか詳しく教えてください。 – xmaestro

+0

(質問にはTSというタグが付いているため) – drewmoore

+1

[Function.prototype.bind](https:///developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/bind)は、適切なコンテキストで 'this.customValidators.usernameTaken'を呼び出す新しい関数を返します。 'this.customValidators.usernameTaken'は動的なコンテキストを持つバリデーターメソッドへの参照にすぎないので、' this'はこのメソッドがどのように呼び出されるかに依存しますが、 'this'は' this.customValidators'を呼び出します。興味深いもの: – dfsq

関連する問題