您的验证器validator.ts
或文件的名称是什么:
// we wrap the validator in a function that we can pass the list of users
// when the validator is created, it caches the list of users
const userNameAsyncValidator = (users: User[]) => (control: FormControl) =>
new Observable((observer: Observer<ValidationErrors | null>) => {
if((control.value !== this.user.userLogin) && users.find(user => this.user.userLogin === control.value)) {
observer.next({ error: true, duplicated: true });
}else {
observer.next(null);
}
observer.complete();
})
})
);
关于你的验证器有几点要说的:
- 如果控制值为空会发生什么?
- 您还需要验证器成为异步验证器吗?
您的组件:
import { validator } from './validator';
@Component({
...
})
class SomeComponent implements OnInit, OnDestroy {
private destroy$ = new Subject();
private userList: User[];
public control = new FormControl(
'',
// we pass the list of referenced users to generate our validator
validator(this.users)
);
constructor(private userService: UserService) {}
ngOnInit() {
// subscribe here and fetch the list of users when the component is instantiated
// and keep a reference
this.userService
.pipe( takeUntil(this.destroy$))
.subscribe(users => this.userList = users)
}
ngOnDestroy() {
this.destroy.next();
this.destroy$.unsubscribe();
}
}