Unidirectional Data for Angular

Where 2-way data flow works great:

  • 1 Endpoint : 1 Model : 1 Viewmodel : 1 View
  • The model (service) isn't always even necessary, and acts as little more than a caching layer or method of sharing data between views.
  • Beautiful active record simplicity.

Where 2-way data flow gets messy

  • Multiple endpoints for a single model.
  • Multiple models for a single viewmodel
  • How? Why!?
  • Other examples?
  • Let's dig in.

Multiple endpoints for a single model: example

  • Fetching a deeply nested model, e.g. v3/submissions, each submission has files, each file has threads, each thread has messages.
  • It would be impractical to "save" this entire model back to the server in order to update "message read by user" status.
  • But we also want this action to update our model locally so that our view updates.
  • Restangular solves some of these problems, but may not be flexible enough for our uses.

Multiple models for a single viewmodel: example

  • The submissions view includes a list of submissions, which need to show where (first, second...) the user has ranked them. This data doesn't live on the submission, but on the step they belong to.
  • Updating the rank of one submission can shuffle the rank of other submissions, and the whole UI needs to reorder appropriately.

One way of doing unidirectional flow in Angular

Drumroll please...

Benefits of unidirectional data flow

  • It's the Angular (2) way!
  • Loading/pending and error states become a lot cleaner to deal with. It makes the viewmodel and view's job to display errors, rather than determine or store them.
  • Your controllers become pure functions of state, which makes them easier to test.
  • Allows your viewmodels to react to changes in the models they observe.
  • Can still use two-way binding between controller and view where appropriate.

Downsides to unidirectional flow

  • Initial complexity is higher
  • Handling unsaved/temp data (think forms) can be messy
  • Others?

Discussion points

  • Does this feel like a useful model for us? Why not?
  • How do we feel about $rootScope as a dispatcher?
  • What about Flux (Redux)?
  • Falcor?

angular-unidirectional

By aselbie

angular-unidirectional

  • 67