비동기유효성검사

lee jae hwan·2022년 9월 29일

앵귤러

목록 보기
72/83

동기유효성검사를 위한 디렉티브방법과 비슷하다.

@Directive({
  selector: '[appUniqueAlterEgo]',
  providers:[{provide:NG_ASYNC_VALIDATORS,useExisting:AlterEgoDirective ,multi:true}]
})
export class AlterEgoDirective implements AsyncValidator {

  validate(control: AbstractControl<any, any>):Observable<ValidationErrors | null> {
    return this.heroesService.isAlterEgoTaken(control.value).pipe(
      map(isTaken=>(isTaken?{uniqueAlterEgo:true}:null)),
      catchError(()=>scheduled([null],queueScheduler))
    );
  }
  constructor(private heroesService:HeroesService) {}

}

AsyncValidator를 구현하고 Observable<ValidationErrors | null> 을 반환하면 된다.


@Injectable({
  providedIn:'root'
})
export class UniqueAlterEgoValidator implements AsyncValidator{

  validate(control: AbstractControl<any, any>): Observable<ValidationErrors | null> {

    return this.heroService.isAlterEgoTaken(control.value).pipe(
      map(isTaken=>(isTaken?{uniqueAlterEgo:true}:null)),
      catchError(()=>scheduled([null],queueScheduler))
    );
  }
  constructor(private heroService:HeroesService){

  }
}


@Directive({
  selector: '[appUniqueAlterEgo]',
  providers:[{provide:NG_ASYNC_VALIDATORS,useExisting:forwardRef(()=>UniqueAlterEgoValidator)
    ,multi:true}]
})
export class AlterEgoDirective {

  constructor(private validator:UniqueAlterEgoValidator) {
  }

  validate(control:AbstractControl){
    this.validator.validate(control);
  }

}

위와 같이 유효성검사를 수행하는 서비스를 만들고 디렉티브에 의존성주입해서 서비스 유효성검사함수를 호출하는 방법도 있다.

0개의 댓글