0

为什么回来是未定义的currentdatethis.currentdate.getTime()

newlisting = this.formBuilder.group({
    availabledate: new FormGroup({
      xyz: new FormControl()
    },[this.mainservice.getcurrenttime.bind(this)])
})
@Injectable({providedIn: 'root'})
export class MainService {

  constructor(){}
 
  currentdate: Date = new Date();

  getcurrenttime(control: FormGroup){

    console.log(this.currentdate.getTime())  <~~ Generates Error!!!

    if(condition){
      return {date: true};
    }
    return null;
  }

}
4

2 回答 2

1

当您执行类似的操作this.mainservice.getcurrenttime.bind(this)时,它会创建一个绑定函数。

由于上面创建的绑定函数,在您的情况下,getcurrenttime()方法内this将被称为YourComponent实例。

由于组件没有任何名为currentdate声明的属性,this.currentdate因此会导致undefined并尝试对其进行读取getTime()将导致错误。


以下是您可以使用的一些替代方案:

  1. 将其绑定到mainservice实例
this.mainservice.getcurrenttime.bind(this.mainservice)
  1. 从下面返回一个 ValidatorFn getcurrenttime,这样您就不会丢失this上下文。(我会推荐这种方法)
// Within MainService
getcurrenttime(): ValidatorFn {
  return (control: AbstractControl) => {
    console.log(this.currentdate.getTime());
    // Your logic
    return null;
  }
}

// Within YourComponent
this.mainservice.getcurrenttime()
  1. 定义getcurrenttime为箭头函数,然后就不需要使用bind.
// Within MainService
getcurrenttime = (control: AbstractControl) => {
  console.log(this.currentdate.getTime());
  // Your logic
  return null;
}

// Within YourComponent
this.mainservice.getcurrenttime  // No need to use .bind(...)

我应该在 Angular 类中将方法编写为箭头函数吗

于 2022-02-13T07:23:44.330 回答
0

不使用 .bind() 设置验证

newlisting = this.formBuilder.group({
    availabledate: new FormGroup({
      XYZ: new FormControl()
    },[this.mainservice.getcurrenttime()])
})

我认为您可以在方法中定义该 currentDate 变量。

 const currentdate: Date = new Date();

我认为你应该返回这样的东西。

getCurrentTime(): ValidatorFn {
    return (formGroup: FormGroup): ValidationErrors | null => {
      const currentDate: Date = new Date();

      const year = formGroup.get('year').value;
      const month = formGroup.get('month').value;
      const day = formGroup.get('day').value;

      const selectedDate = new Date(year, month, day, 0, 0, 0, 0);

      if (selectedDate === currentDate) {
        formGroup.setErrors({ any_error: true }); // on your form group
        return null;
      } else return null;
    };
  }
于 2022-02-13T05:54:53.687 回答