0

我一直在寻找很多关于以角度将异步验证器实现为反应形式的教程,我对以下代码有疑问。

  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 内部的 observable 订阅是一种不好的做法吗?

4

1 回答 1

0

您的验证器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();
   }
 }
于 2020-11-09T15:01:22.053 回答