2016-08-11 6 views
5

カスタム非同期バリデーターを作成しようとしています。これはサーバーに送られ、電子メールがすでに登録されているかどうかを確認します。角2のカスタム非同期検証でHttpが動作しない

残念ながら、何も起こらないため、getリクエストは実行されないようです。私はsubscribeの中に複数のconsole.logを試しましたが、実行されませんでした。

そのリクエストがバリデータの外部で機能しているかどうかを確認しましたが、それは問題ではありません。

import { Component } from '@angular/core'; 
import { FormGroup, FormBuilder, Validators, FormControl } from '@angular/forms'; 
import { Response, Http } from '@angular/http'; 

@Component({ 
    templateUrl: 'build/pages/welcome/signup/signup.html', 
    providers: [AuthService, CustomValidators] 
}) 
export class Signup { 

    signupForm: FormGroup; 

    constructor(private formBuilder: FormBuilder, private http: Http) { 

     this.signupForm = formBuilder.group({ 
      'email': ['', Validators.required, this.checkEmail], 
     }): 
    } 

    checkEmail(control: FormControl): Promise<any> { 

      const promise = new Promise<any>(
      (resolve, reject) => { 

       this.http.get('/sharealead/main.php?action=checkEmail').subscribe(
        (res: Response) => { 
         console.log('it never gets here'); 
         console.log(res) 
         if (res.text() == 'already there') { 
          resolve({'emailTaken': true}); 
         } else { 
          resolve(null); 
         } 
        }, 
        (err) => { 
         console.log('it never gets here'); 
         console.log(err); 
        } 
       ) 
      } 
     ); 
     return promise; 
    } 

} 

答えて

8

この機能を参照すると、thisというコンテキストが失われるためです。あなたは(コンポーネントインスタンスに機能をリンク)これを修正するためにbind方法やラッピング矢印機能を使用することができます。

this.signupForm = formBuilder.group({ 
     'email': ['', Validators.required, this.checkEmail.bind(this) ], 
}); 

または

this.signupForm = formBuilder.group({ 
     'email': ['', Validators.required, (control:Control) => { 
      return this.checkEmail(control); 
     } ], 
}); 

あなたのケースでは、thishttpが含まれていませんプロパティ...

+0

実際には、愚かな間違いは、私はJavaScriptでこのキーワードについてのもう一つの教訓が必要なように見えます(私はあなたの答えを約8分で受け入れるとマークします、stackoverflowは私にできます) –

+0

よろしくお願いします!はい、JavaScriptで 'this'キーワードを使用するのはちょっと具体的です... –

+0

フィールドのぼかしだけでバリデータートリガーを作成する方法も教えてください。私の場合、テキストボックスに電子メールを入力している間でも、httpリクエストを送信しています。私のメールアドレスを入力する前に、既にサーバにいくつかのリクエストを送っています –

関連する問題