為什么回來是未定義的currentdate?this.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;
}
}
uj5u.com熱心網友回復:
當您執行類似的操作this.mainservice.getcurrenttime.bind(this)時,它會創建一個系結函式。
由于上面創建的系結函式,在您的情況下,getcurrenttime()方法內this將被稱為YourComponent實體。
由于組件沒有任何名為currentdate宣告的屬性,this.currentdate因此會導致undefined并嘗試對其進行讀取getTime()將導致錯誤。
以下是您可以使用的一些替代方案:
- 將其系結到
mainservice實體
this.mainservice.getcurrenttime.bind(this.mainservice)
- 從下面回傳一個 ValidatorFn
getcurrenttime,這樣您就不會丟失this背景關系。(我會推薦這種方法)
// Within MainService
getcurrenttime(): ValidatorFn {
return (control: AbstractControl) => {
console.log(this.currentdate.getTime());
// Your logic
return null;
}
}
// Within YourComponent
this.mainservice.getcurrenttime()
- 定義
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 類中將方法撰寫為箭頭函式嗎
uj5u.com熱心網友回復:
不使用 .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;
};
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/430506.html
上一篇:操作有條件渲染的元素
