在自定义异步验证器中订阅是错误的吗?应该会降低性能吗?

问题描述

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

  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();
   }
 }

相关问答

Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其...
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。...
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbc...