在自定义验证器中使用 Observable Angular
Using Observable inside Custom Validator Angular
所以我正在创建一个验证器来检查用户名是否已被使用。
我有以下自定义验证器定义:
import { AbstractControl } from '@angular/forms';
import { AccountApi } from '../../api/service/account.api';
import { Injectable } from '@angular/core';
import { switchMap, mapTo, catchError } from 'rxjs/operators';
import { of, timer } from 'rxjs';
@Injectable()
export class UsernameValidator {
constructor(private api: AccountApi) {
}
exists(control: AbstractControl) {
// this.api.checkUsernameIfExisting(control.value).subscribe((existing) => {
// control.setErrors({ exists: existing });
// });
// return null;
return timer(100).pipe(
switchMap(() => this.api.checkUsernameIfExisting(control.value).pipe(
// Successful response, set validator to null
mapTo(null),
// Set error object on error response
catchError(() => of({ exists: true }))
)
)
);
}
}
我是这样使用的:
username: ['', [
Validators.required,
Validators.minLength(6),
Validators.maxLength(30),
this.usernameValidator.exists.bind(this.usernameValidator)
]],
我的问题是,为什么我的 API 上的呼叫没有被触发?我检查了表单是否正在调用 exists() 并且它调用了它。
谢谢!
异步验证器应该在同步验证器之后。
所以我会尝试这样的事情:
username: ['', [
Validators.required,
Validators.minLength(6),
Validators.maxLength(30),
],
this.usernameValidator.exists.bind(this.usernameValidator)
],
所以我正在创建一个验证器来检查用户名是否已被使用。
我有以下自定义验证器定义:
import { AbstractControl } from '@angular/forms';
import { AccountApi } from '../../api/service/account.api';
import { Injectable } from '@angular/core';
import { switchMap, mapTo, catchError } from 'rxjs/operators';
import { of, timer } from 'rxjs';
@Injectable()
export class UsernameValidator {
constructor(private api: AccountApi) {
}
exists(control: AbstractControl) {
// this.api.checkUsernameIfExisting(control.value).subscribe((existing) => {
// control.setErrors({ exists: existing });
// });
// return null;
return timer(100).pipe(
switchMap(() => this.api.checkUsernameIfExisting(control.value).pipe(
// Successful response, set validator to null
mapTo(null),
// Set error object on error response
catchError(() => of({ exists: true }))
)
)
);
}
}
我是这样使用的:
username: ['', [
Validators.required,
Validators.minLength(6),
Validators.maxLength(30),
this.usernameValidator.exists.bind(this.usernameValidator)
]],
我的问题是,为什么我的 API 上的呼叫没有被触发?我检查了表单是否正在调用 exists() 并且它调用了它。
谢谢!
异步验证器应该在同步验证器之后。
所以我会尝试这样的事情:
username: ['', [
Validators.required,
Validators.minLength(6),
Validators.maxLength(30),
],
this.usernameValidator.exists.bind(this.usernameValidator)
],