In my Angular 5 application, I am utilizing the reactive forms approach.
Within an Angular Material dialog, I have a form that is used for both data entry and editing. The constructor in my code looks like this:
constructor(public formBuilder: FormBuilder,
public documentService: DocumentService,
@Inject(MAT_DIALOG_DATA) public data: any) {
this.createForm();
if (this.data.edit) {
this.setValues();
}
this.setTitles();
}
The createForm
function creates a reactive form with async validation:
createForm() {
this.documentForm = this.formBuilder.group({
...
documentNumber: new FormControl('',
{
updateOn: 'blur',
validators: [Validators.required],
asyncValidators: [this.checkDocumentNumber.bind(this)]
}),
...
});
}
If the dialog is in 'edit' mode, the setValues
function is called to populate the form fields that need editing:
setValue() {
this.form.patchData({
...
documentNumber: this.data.document.documentNumber
...
});
}
The setTitles
function sets the title of the dialog.
The checkDocumentNumber
method validates a document number using an API call:
checkDocumentNumber(control: AbstractControl): Observable<ValidationErrors | null> {
const formValue = this.form.value;
return this.documentService
.checkDocumentNumber(new Document(this.data.edit ? this.data.document.id : 0,
form.documentNumber)).pipe(map((response: boolean) => {
return response ? { inUse: true } : null;
}));
}
The API call made is:
checkDocumentNumber(doc: Document) {
return this.http.post(`/Documents/Inbox/CheckDocumentNumber`, doc);
}
To open the form dialog in 'edit' mode, you can use the following code:
this.dialogService.open(DocumentDialogComponent,
{
data: {
edit: true,
document: this.document
}
});
An issue arises when I attempt to edit document data within the dialog. Multiple unnecessary API calls are being triggered, resulting in delays. How can I prevent Angular from making these redundant API calls? I believed that the addition of the updateOn
flag in Angular 5 would address this, but it seems to persist.
For reference, here is a snapshot showing the API calls being initiated: