问题描述
我一直在寻找很多关于以角度的方式将异步验证器实现为反应形式的教程,我对下面的代码有疑问。
userNameAsyncValidator = (control: FormControl) =>
new Observable((observer: Observer<ValidationErrors | null>) => {
this.useRSService.getUsers().subscribe(users => {
if((control.value !== this.user.userLogin) && users.find(user => user.userLogin === control.value)) {
observer.next({ error: true,duplicated: true });
}else {
observer.next(null);
}
observer.complete();
})
});
这是处理此问题的最佳方法吗?从de asyncValidator内部的可观察对象订阅是一种不好的做法吗?
解决方法
您的验证者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();
})
})
);
关于您的验证者的两件事:
- 如果控制值为null,会发生什么?
- 您还需要验证器成为异步验证器吗?
您的组件:
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();
}
}