Chatty REST API Calls in Angular Forms

AngularJS Single Page Apps are great at interacting with REST APIs.  A common capability we’ve come to use is invoking PATCH operations on an Angular form using two way data binding with an API resource.

The question is when and how often we should update the API resource.

  • Once per form submission?
  • Once per form section?
  • Or every time a field is updated?

We realized that there are very good reasons to keep the resource updated every time a field changes.  In a multi-user environment, having a client hold on to changes can be risky, so frequent updates use useful.  Furthermore, even within a single resource representation, there can be dependencies in which the value of an attribute can affect the value of another attribute.

It was trickier than expected to find the optimal AngularJS technique to keeping resources updated.

The obvious choice is to call PATCH on ngBlur, but that means that we’re hitting the API even if the user simply tabs/clicks in and out of a form field.

What we really want is to identify when the value of a field has been changed by the user.  So ngChange? Turns out that ngChange is called on each keypress, so we certainly don’t want to PATCH that frequently.

The answer turned out to be a combination of the two.  ngBlur with the updateOn attribute of ngModelOptions!

Codepen link

Chatty REST API Calls in Angular Forms

Leave a Reply

Your email address will not be published. Required fields are marked *