4-way Data-binding: Offline
Data Synchronization in
AngularJS
http://zndg.tl/ng-pouchdb
Daniel Zen
@zendigital
admin@zen.digital
My Background
Systems Architect, Developer & Trainer
Agile Engineering / XP Background
Started AngularJS-NYC Meetup mid-2012
Formed zen.digital in 2014
User Experience for Web & Mobile
Scalable MicroService based APIs
Best Practices for Development & Deployment
Corporate Training
Full Stack JavaScript
Node.js
MongoDb
etc.
Outline for this talk:
Requirements for AngularJS data models
Standard Online Techniques
CRUD, RESTful APIs
$http, $resource
Higher Level Abstractions
Offline issues
local storage options
Sample Application walk through
http://github.com/danielzen/todo-ng-pouchdb
ng-PouchDb Collection & Binding
Requirements for data models
in AngularJS:
Requirements for models in
AngularJS:
ABSOLUTELY
NOTHING
AngularJS is model agnostic
Any variable or object can serve as a
model
No unique ID required
No built-in persistence model for objects
ng-model binds javascript variables
to UI not to backend
What does this mean for data
persistence
There is no standard, yet
Angular 2 did not add one
Various open source storage options
SQL
MySQL
PostgreSQL
NoSQL
MongoDB
CouchDB
Common Persistence Practices
CRUD Create, read, update and delete
Each letter in the acronym can map to
a standard
SQL
statement and HTTP
Operation`
SQL
HTTP
method:
Create
INSER PUT / POST
T
Read
(Retrieve)
SELEC GET
T
Update
(Modify)
UPDAT PUT /
E
PATCH
Delete
(Destroy)
DELET DELETE
E
Typically we employ CRUD via
RESTful APIs
RESTful APIs Representational state transfer
The name Representational State Transfer is
intended to evoke an image of how a welldesigned Web application behaves: a network
of Web pages forms a virtual state machine,
allowing a user to progress through the
application by selecting a link or submitting a
short data-entry form, with each action
resulting in a transition to the next state of
the application by transferring a
representation of that state to the user. - Roy
Fielding
Common REST Practices
Reso
urce
PO
ST
crea
te
GET
read
PUT
upda
te
DEL
ETE
delet
e
/
acco
unts
Cre
ate
a
new
acc
ount
List
acco
unts
Bulk
upda
te
acco
unts
Dele
te all
acco
unts
/
acco
unts/
123
Erro
r
Sho
w
acco
unt
123
If
exist
s
upda
te
acco
unt
123
Dele
te
acco
unt
123
If not
error
$http Service
The AngularJS XmlHttpRequest API
follows the Promise interface ($q
service)
Returns a promise object with the standard
$http({method:
'GET',
'/someUrl'}).
then
method
andurl:
two
http specific methods:
success(function(data, status, headers, config) {
success
error.
// thisand
callback
will be called asynchronously
// when the response is available
}).
error(function(data, status, headers, config) {
// called asynchronously if an error occurs
// or server returns response with an error
status.
});
$resource - a higher level
abstraction
service in module ngResource
factory lets you interact with server-side
data
returns resource with methods for CRUD
(Create, Read, Update, Delete)
operations: get, save, query, remove, delete
operations can be invoked by the
following:
no need to interact with the low level
$http
More reference:
But what about offline (&
higher level)?
Web apps no longer dependent on
servers
Solution: richer clients (using
AngularJS ;)
Google Docs is a good example
For offline first experience:
You need to store the data in the front end
You need it to sync to the servers data store.
In browser databases available:
derby.js, Lawnchair, Sench touch
requirement: online synchronization
What have we come to expect
Email should work offline
Local copy of recent emails
Can read or delete
Can write new emails, and will send when
online
Google Docs keeps pushing threshold
In Chrome we can view and edit while offline
mobile version now has offline edit capability
Conflict resolution
Intelligently merge documents with multiple
edits
Connectivity Lifecycle
Failures can happen on: client push, or client pull/
server push
Communicate or hide connectivity state
Chat app
Enable client-side creation and editing
features
Todo app
Disable, modify, or hide features that
wont work
Facebook status, Twitter Tweets
Notify user about possibly conflicting
data
How to deal with being offline
You are offline
Unable to connect to the Internet
We need to stop treating offline as an error
condition
Try not to block features completely
If you cant update, show old data (with
message)
Let user create data locally to be sent later
Dealing with new incoming data.
Options:
Show it as the most recent
Show it in chronological order
So what are local storage
options?
Wait for AngularJS 2.0
Roll your own!
Use localstorage, indexDb, or WebSql directly
Proprietary solution?
Firebase (AngularFire)
Firebase transparently reconnects to server
But doesnt persist to local storage
Open source local storage databases
that sync
Hoodie (Another JS db that syncs. In preview
mode)
remotestorage.io (IETF Proposed Standard)
PouchDB (JavaScript database that syncs!)
Firebase
Pros
AngularJS library (AngularFire)
3-way binding with $bind
Free Developer (Hacker) plan
Paid solution with premium support
Hosted solution
Can deploy static hosted apps
Cons
Proprietary solution
Hosted solution (cant run local or on own
servers)
No local storage solution
PouchDB
Pros:
Open Source
Lightweight Cross Browser JavaScript
implementation
Syncs with open source CouchDB protocol
servers
PouchDB-Server - a HTTP on top of PouchDB
Cloudant - A cluster aware fork of CouchDB
Couchbase Sync Gateway
Cons:
No Standard AngularJS library (yet)
angular-pouchdb is a decent wrapper
Sample Application: todo-ngpouchdb
Source code is available at:
https://github.com/danielzen/todo-ng-pouchdb
Uses ionic hybrid mobile app framework
Pre-requisites:
Node
CouchDb
2-Way Data Binding AngularJS
User Interface
(DOM)
Data Model
(JavaScript)
3-Way Data Binding AngularFire
User Interface
(DOM)
Data Model
Data Model
(JavaScript)
Internet
Database
(Firebase)
4-Way Data Binding - ngpouchdb
User Interface
(DOM)
Data Model
Data Model
(JavaScript)
Local Storage
(PouchDb)
Internet
Database
(CouchDb)
Sample Application: ngpouchdb
Source code is available at:
http://github.com/danielzen/todo-ng-pouchdb
Uses angular-pouchdb wrapper
wraps pouchs methods with Angular Promise
($q)
Pre-requisites:
Node
CouchDb
for 4-way sync
Resources
Data Persistence in Angular 2.0
Designing Offline - Alex Feyerke
Building offline applications with AngularJS and PouchDB
Sync multiple AngularJS apps without server via PouchDB
TodoMVC (AngularJS) + Hood.ie = 60 minutes to awesome
A copy of these slides is
available at:
http://zndg.tl/ng-pouchdb