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]
コメントを追加