angularvalidationangular-custom-validators

Angular: Cyclic Dependency


Why is currentdate in this.currentdate.getTime() coming back as undefined?

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

}

Solution

  • When you do something like this.mainservice.getcurrenttime.bind(this), it creates a bound function.

    Due to the above created bound function, in your case within getcurrenttime() method this would be referred to as YourComponent instance.

    Since the component doesn't have any property named currentdate declared, this.currentdate will result in undefined and trying to read getTime() on it will result in an error.


    Below are few of the alternatives you can use:

    1. Bind it to the mainservice instance
    this.mainservice.getcurrenttime.bind(this.mainservice)
    
    1. Return a ValidatorFn from getcurrenttime as below, so that you don't lose the this context. (I would recommend this approach)
    // Within MainService
    getcurrenttime(): ValidatorFn {
      return (control: AbstractControl) => {
        console.log(this.currentdate.getTime());
        // Your logic
        return null;
      }
    }
    
    // Within YourComponent
    this.mainservice.getcurrenttime()
    
    1. Define getcurrenttime as an arrow function and then you don't need to use 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(...)
    

    Should I write methods as arrow functions in Angular class