We have a pretty nested reactive Angular from with all of the FormControls inside a FormGroup which is inside a FormArray. A few of the FormControls have async validators to check for the uniqueness of the values. All the async validators are called every time another FormGroup gets added/removed to/from the FromArray dynamically.
Eg:
FormGroup.addControl
FromGroup.removeControl
Let's say I have 5 FormControls with async validators on them, and then if I added another 4 FormControls dynamically (addControl), 4*5=20 times async validators gets called, and a lot of the times few of those Http calls gets canceled. I am assuming Angular must be using switchMap under the hood somewhere which results in canceling of some of the Http calls made from async validators.
Can someone please shed some light on this? How do I resolve this problem or what are some of the best practices with Async validators in Angular?
In Angular, when you have a reactive form with async validators, Angular indeed uses switchMap to manage the ongoing observable streams. This behavior can lead to the cancellation of ongoing HTTP requests when new validations are triggered.
Here are a few strategies to handle this issue and improve the performance of your async validators:
Debouncing Requests: Use a debounce time to delay the execution of async validators, so that they are not triggered immediately upon every change. This can help in reducing the number of unnecessary HTTP requests.
Take Until Operator: Use the takeUntil operator to complete the ongoing observable when the component is destroyed or when the form control is removed. This can help in avoiding unnecessary ongoing requests for removed form controls.
FormGroup Cleanup: Ensure that you clean up form controls and async validators properly when a form group is destroyed or a form control is removed.
Optimizing Async Validators: Review your async validator logic to ensure it is as efficient as possible. Minimize unnecessary requests, and consider server-side pagination or filtering if applicable.
Applying these strategies should help you optimize the behavior of async validators in your Angular reactive forms and reduce the number of canceled HTTP requests. Adjust the debounce time and other parameters based on your specific use case and requirements.