フォーム制御の非同期検証の問題

aRtoo

Angular2に非同期検証を実装しようとしていますが、何らかの理由で何かを入力しようとすると、デバウンスが機能しません。入力に応じて複数回トリガーされます。また、ロード時に非同期バリデーターがトリガーされ、ステータスが保留に設定されるため、情報ボックスに表示されますchecking...

これが私がそれを実装する方法です:

HTML:

 <div class="form-group d-flex col px-0">
   <label for="coupon" class="col-2">coupon_code:</label
    <div class="col-5 pl-4 pr-0">
     <input
      class="form-control"
      id="coupon"
      type="text"
      name="coupon"
      formControlName="coupon"
      autocomplete="off"
      />
 </div>

TSファイル

形:

initForm() {
    const email = '';
    const password = '';
    const password_confirmation = '';
    const doctor = '';
    // const license = '';
    const type = 'doctor';
    const company_id = '';
    const corporate_token = '';
    const doctorLastName = '';

    this.signUpForm = this.fb.group(
      {
        coupon: ['',[], this.couponAsyncValidation.bind(this)]
      },
      {
        validator: this.signupFormValidator(),
      }
    );
  }

非同期検証コード:

 couponAsyncValidation(control: FormControl): Promise<any | null> | Observable<any | null> {
     return new Promise( (res, rej) => {
      control.valueChanges.pipe(
        debounceTime(2000),
        distinctUntilChanged(),
        switchMap(value => this.userService.couponChecker(value)),
        map( (q) => q ),
        first()
      ).subscribe(
        (d) => { 
        console.log(d)
         d.is_coupon_valid ? res(null) : res({invalid: true})
        }
      )
    })
  }

couponAsyncValidation ロード時にトリガーされ、入力に触れていなくてもステータスは保留中です。

更新

私はなんとかステータスを処理することができました。ステータスと保留中、およびダーティかどうかを確認しました。

残っている問題は、debounceTimerが機能しないことです

更新私は観察可能な機能が欠けていると思います。どう思いますか?

UPDATEは、2秒後に送信されるリクエストの画像です。

ここに画像の説明を入力してください

デバウンスが機能しない理由はありますか?

更新

これは@jarekの助けを借りて現在機能しています。

これが非同期検証の完全なコードです


import { AbstractControl, AsyncValidatorFn } from '@angular/forms';
import { switchMap, map} from 'rxjs/operators';
import { UserService } from '../user/services/user.service';
import { Observable, timer, of } from 'rxjs';

export class AsyncValidator {
  static couponValidator(miliSec: number, service: UserService): AsyncValidatorFn {
    return (control: AbstractControl): Observable<any | null> => {
      return timer(miliSec).pipe(
        switchMap(() => {
          if ( control.value ) {
            return service.couponChecker(control.value);
          }
          // this one is needed because for some reason on loading, the signup page
          // will immediately trigger this async call which sends a request to the backend
          // even though user has not inputted anything.
          // then sets the status of the form to pending thus resulting to an invalid form
          return of({is_coupon_valid: true});
        }),
        map( (res) =>  res.is_coupon_valid ? null : res )
      );
    };
  }
}

ジャレック

あなたはそのようなものが欲しいですか?

https://stackblitz.com/edit/angular-reactive-forms-async-validator-2nkefw

最高のジャレック

この記事はインターネットから収集されたものであり、転載の際にはソースを示してください。

侵害の場合は、連絡してください[email protected]

編集
0

コメントを追加

0

関連記事

TOP 一覧

  1. 1

    PictureBoxで画像のブレンドを無効にする

  2. 2

    Pythonを使用して、リストからデータを読み取り、特定の値をElasticsearchにインデックス付けするにはどうすればよいですか?

  3. 3

    Rパッケージ「AppliedPredictiveModeling」のインストール中にエラーが発生しました

  4. 4

    C ++でのcURLとマルチスレッドの使用

  5. 5

    Chromeウェブアプリのウェブビューの高さの問題

  6. 6

    セレンのモデルダイアログからテキストを抽出するにはどうすればよいですか?

  7. 7

    Python / SciPyのピーク検出アルゴリズム

  8. 8

    Spring @ModelAttributeモデルフィールドマッピング

  9. 9

    STSでループプロセス「クラスパス通知の送信」のループを停止する方法

  10. 10

    tkinterウィンドウを閉じてもPythonプログラムが終了しない

  11. 11

    tf.nn_conv2dとtf.nn.depthwise_conv2dの違い

  12. 12

    Ansibleで複数行のシェルスクリプトを実行する方法

  13. 13

    MLでのデータ前処理の背後にある直感

  14. 14

    Windows 10 Pro 1709を1803、1809、または1903に更新しますか?

  15. 15

    MyBatisがネストされたオブジェクト属性を参照するとOgnlExceptionが発生します

  16. 16

    java.lang.NoClassDefFoundError:com / sun / istack / tools / DefaultAuthenticator $ Receiver

  17. 17

    テキストフィールドの値に基づいて UIslider を移動します

  18. 18

    HTTPヘッダー 'SOAPAction'の値はサーバーによって認識されませんでした

  19. 19

    BLOBストレージからデータを読み取り、Azure関数アプリを使用してデータにアクセスする方法

  20. 20

    追加後、ブートストラップマルチセレクトがテーブルで機能しない

  21. 21

    レスポンシブウェブサイトの一番下にスティッキーなナビゲーションバーを作成するのに問題がある

ホットタグ

アーカイブ