首页 > 解决方案 > 如何将值传递给验证器以便在角度 5 中保存服务调用?

问题描述

我有来自 ts 文件(组件)的以下代码:

ngOnInit() {
  this.getTripNames();
}

getInstruments() {
  this.tripService.getTripNames().subscribe(
    data => { this.tripNames = data; },
    err => console.error(err),
    () =>
      console.log(this.trips)
  );
}

ngAfterViewInit() {
  this.tripForm = new FormGroup({
    newTripName: new FormControl('', {
      validators: Validators.compose([
        Validators.required,
        Validators.minLength(3),
        ValidateTrip.createValidator(this.tripNames)
      ]),
      updateOn: 'blur'
    })
  });

}

如您所见,行程是在加载组件时获取的(它们显示在页面上以及控制台上),问题是这些值在Validator处理时不可用。被createValidator调用,但值未定义。我可以向验证器注入服务并再次从 restful 服务中获取值,但这没有任何意义。知道如何在this.tripNames内部提供Validator吗?谢谢。

标签: angularangular-validator

解决方案


根据 http 请求或其他 observable 进行验证时,您需要使用asyncValidator 。

ngAfterViewInit() {
  this.tripForm = new FormGroup ({
    newTripName: new FormControl('', {
      validators:  Validators.compose([
        Validators.required,
        Validators.minLength(3)
      ]),
      asyncValidators: [tripNamesValidator.bind(this)],
      updateOn: 'blur'
    })
  });
}

tripNamesValidator() {
  return this.tripService.getTripNames()
    .map(tripNames=>{
      return youCondition?null:{errorName: 'error message'};
   }); 
}

推荐阅读