我目前正在開發一個 api 的前端,其中我有一個 Input 欄位,只要輸入不是唯一的,我想驗證它以禁用提交按鈕。
我的組件看起來有點像這樣:
export class CategoryCreateComponent implements OnInit {
categoryNamesInUse: Category[];
categoryCreateForm: FormGroup;
constructor(private categoryService: CategoryService) {}
ngOnInit(): void {
this.getAllUsedNames();
this.categoryCreateForm = new FormGroup({
categoryName: new FormControl('', [
Validators.required,
Validators.minLength(1),
this.invalidCategoryNames.bind(this),
]),
});
}
getAllUsedNames() {
this.categoryService
.findAllByUser()
.pipe(
map((categories) => {
const usedNames = [];
for (const key in categories) {
usedNames.push(categories[key].name);
}
return usedNames;
})
)
.subscribe((categoryNames) => (this.categoryNamesInUse = categoryNames));
}
invalidCategoryNames(control: FormControl): { [message: string]: boolean } {
if (this.categoryNamesInUse.indexOf(control.value) !== -1) {
return { categoryNameAlreadyInUse: true };
}
return null;
}
}
問題是 categoryNamesInUse[] 未定義,我不知道如何等待我的 getAllUsedNames() 方法。
uj5u.com熱心網友回復:
Ozan 的回答是正確的,但我會提供您可能更喜歡的async/解決方案。await
async ngOnInit(): Promise<void> {
await this.getAllUsedNames();
this.categoryCreateForm = new FormGroup({
categoryName: new FormControl('', [
Validators.required,
Validators.minLength(1),
this.invalidCategoryNames.bind(this),
]),
});
}
getAllUsedNames(): Promise<void> {
return new Promise<void>((resolve) => {
this.categoryService
.findAllByUser()
.pipe(
map((categories: any[]) => {
const usedNames = [];
for (const key in categories) {
usedNames.push(categories[key].name);
}
return usedNames;
})
)
.subscribe((categoryNames: any) => {
this.categoryNamesInUse = categoryNames;
resolve();
});
});
}
uj5u.com熱心網友回復:
我猜你不會直接分享你的代碼,所以我不確定,但你可以定義一個布爾變數(isSubmitButtonDisabled = true)并移動這部分:
this.categoryCreateForm = new FormGroup({
categoryName: new FormControl('', [
Validators.required,
Validators.minLength(1),
this.invalidCategoryNames.bind(this),
]),
});
進入這里:
.subscribe((categoryNames) => {
this.categoryNamesInUse = categoryNames;
--moved block--
isSubmitButtonDisabled = false;
});
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/427687.html
