Single Page Applications with AngularJS 2.0

Sumanth Chinthagunta
Sumanth ChinthaguntaPrincipal Engineer at UnitedHealth Group
Single Page Applications 2.0
Push the limits of what’s possible on the web
New Topics
• Tool Chain, Code Organization
• Asset pipeline hooks
• Programmable CSS with SASS and Bourbon
• Transpile ES6  ES5
• ES6/ES7 with Angular
• AMD with Angular
• DI 2.0 with Angular
• HTML5 Custom Elements
• Functional Reactive Programming with Angular
• NG- Patterns : Logging, Security, Resiliency, Cache
Tool Chain
Gulp - Task Runner
• The streaming build system. No more temp files.
• Gulp replace Grunt.
– Install: npm install -g generator-gulp-angular
– Run: yo gulp-angular [app-name]
– Run gulp for building and gulp watch for preview
gulpfile.js
Gulp and its NPM packages
• Built-in preview server with LiveReload, file watcher
• CSS Pre-processing : SASS, Bourbon Mixins
• CSS Autoprefixing : add vendor prefixes
• JSHinting, CSSLinting : lint your scripts, CSS
• JS Transpilers: ES6  ES5
• Awesome Image Optimization, WebP
• AMD/RequireJS Support
• Concatenation/Optimization, Minification, uglify
• Automatically wire-up dependencies installed with
Bower (when gulp watch or gulp wiredep)
Single Page Applications with AngularJS 2.0
Single Page Applications with AngularJS 2.0
Code Organization
• Adopt De Facto Standards
– Yeomen generated project structure
– Rapid prototyping using scaffolding generators
• Modularity: Organize your files by Feature not by Type
– Modules are independent WebApp functionality that developers can
work in parallel
– Isolate complexity into separate pluggable modules
– In an AngularJS context, modularization is organization by function
instead of type.
• Everything that gets deployed is in the app directory.
• Everything outside of the app directory is for
development
Compose Apps by assembling smaller modules
Organize Files : by Feature, Not by Type
Common/
elements/
myElementTemplate.html
MyElement.js
services/
i18nService.js
filters/
i18nFilter.js
i18b/
en_EN.json
de_DE.json
Index.js
orders/
elements/
tableTemplate.html
TableElement.js
table.css
services/
OrderService.js
index.js
home/
controllers/
HomeController.js
LoginController.js
services/
UserService.js
AuthenticationService.js
i18b/
en_EN.json
de_DE.json
index.js
index.js
../views/
home/
home.html
orders/
order.html
order.details.html
Scalable and Modular layout for
stylesheets/
|
|-- admin/ # Admin sub-project
| |-- modules/
| |-- partials/
| `-- _base.scss
|
|-- account/ # Account sub-project
| |-- modules/
| |-- partials/
| `-- _base.scss
|
|-- site/ # Site sub-project
| |-- modules/
| |-- partials/
| `-- _base.scss
|
|-- vendor/ # CSS or Sass from other projects
| |-- _colorpicker-1.1.scss # in Bower case, under bower_components
| |-- _jquery.ui.core-1.9.1.scss
| ...
|
|-- admin.scss # Primary stylesheets for each sub-project
|-- account.scss
|-- _variables.scss
`-- site.scss
Write leaner, programmable, and
maintainable CSS with SASS & Bourbon
AMD with Angular
Components
Modules
Root Module
Bootstrap
Config Config.js
Bootstrap.js
index.js
Home
Index.js
routes.js
Controllers
Services
Elements
Account
Index.js
routes.js
Controllers
Services
Elements
Common
Index.js
routes.js
Controllers
Services
Elements
Dashboard
Index.js
routes.js
Controllers
Services
Elements
Scripts loading with AMD
Testability
Why do you need to write tests?
– Because you’re not Chuck Norris.
Unit Testing
Karma: Spectacular Test Runner using real browsers!
– Jasmine: behavior-driven development framework for
testing JavaScript code.
– Mocha: Simple, flexible JavaScript test framework.
PhantomJS: Headless Testing
Integration Testing
– Protractor: AngularJS E2E Testing Framework
gulp test command transpile ES6 tests and perform all unit and integration tests
User story: “As a user, when I login to my app, I am taken to the dashboard page.”
ECMAScript 6.0
You Can’t Afford to Avoid ES6
Author In ES6, Transpile To ES5 As A
Build-step: Gulp Workflow
Traceur & Polyfills
Traceur and Shim/Polyfill makes it possible to use
tomorrows technology now!
– Traceur is a JavaScript.next  JavaScript.now compiler
– “A polyfill is a piece of code (or plugin) that provides the
technology that you, the developer, expect the browser to
provide natively. Flattening the API landscape if you will.”
( from Remy Sharp blog)
Traceur provide ES6 that are not available in any browser yet.
Polyfill provide HTML5/ES6 features that are not available in some of the
browsers yet.
ES6 Goodies
• Modules, Classes, Typed, Traits
• Generator, Promises, Proxies
• Closures / Fat Arrow Functions
• Let, Const, Private scope and Block Functions
• Destructuring, For-Of and Array Comprehensions
• Spread Operator, Rest Parameter, and Default
Arguments
• Template Strings, string interpolation
• Collections : Set, Map, Weak Set/Map, Binary Data
• ES7 Object.observe , async/await functions
Single Page Applications with AngularJS 2.0
Promises
Promises are useful when you want to represent the outcome of an
action or a value that will be available at some future time.
– It is an easy way to avoid writing the Pyramid of Doom
– Function return a promise - no more callback parameter
– A promise represents an eventual outcome
– Promises can be pending, fulfilled or rejected
– they are only resolved once;
– Guaranteed to always be async.
– Promises can be chained. Re-tryable
– Promises as first-class objects
– “then-able” objects. then() method returns another promise and you can
return data from the callback to the next promise in the chain.
– A deferred is an object representing work that is not yet done and a
promise is an object representing a value that is not yet known.
Promise Combinators:
Promise.all([p1,p2,p3]) , Promise.race([p1,p2,p3]) , Promise.any([p1,p2,p3])
Single Page Applications with AngularJS 2.0
Promises fix callback hell of async code
Single Page Applications with AngularJS 2.0
Promise Chaining
Asynchronous Control Flow with Promises
Promises are a replacement for Callbacks to help you deal with composition of multiple async
operations while also making error handling simpler in some cases.
What's the Big Deal with Generators?
"First-class coroutines, represented as objects encapsulating suspended execution contexts
(i.e., function activations)”
 Allows suspension of a function's execution until resolved - everything else outside of that
execution continues. Higher-order functions
 Uses a yield statement instead of a return to report values.
 The essence of generator is controlling the suspension of code execution. Caller control execution
of code in Generator function.
Use Cases
• Infinite iterator : Good for representing infinite sequences. Generator return iterators.
• Non-blocking I/O : When we don't yield execution, we're blocking.
• Demand-driven: functions can interactively yield partial results as soon as available.
• Lazy Sequences: We can rewrite lazy version of Underscore.js using Generators. Since
filter and map return generators, nothing happens until reduce. You can get benefits of
declarative functional data manipulation without the performance and memory
downsides of intermediate arrays.
• Run-to-completion(RTC) is a scheduling model in which each task runs until it either
finishes, or explicitly yields control back to the scheduler.
• Flow Control: you can actually pass data back in to the generator, causing yield to either
return a value or throw an exception inside the generator body.
• Synchronously looking Asynchronous code: “Async functions are a thin sugar over
generators and a spawn function which converts generators into promise objects”
Generators Use case Scenarios
This is a big deal: generators finally provide us with a pseudo-synchronous syntax that doesn't
break run-to-completion semantics, doesn't require transpiling, and doesn't require callbacks.
Basic Examples Control Flow
Parallel Loops
Generators makes it possible write
async code that looks like synchronous
ES7 async / await functions
AOP in JavaScript
• ES6 Proxies and Angular Decorators enable
augmenting new behaviors to existing JS Objects
and classes at runtime.
• Can be used along with Traceur’s Annotations (ES6+)
to add cross-cutting concerns by scanning
annotations during application bootstrap process.
• Angular 2.0 Dependency Injection will adopt this
approach.
• Retry aspect has been implemented using this
technique in SPA Starter Kit.
Single Page Applications with AngularJS 2.0
Functional Programming
What is FP?
A style which utilizes HOFs and minimize side effects.
Why FP?
Parallelization , Concurrency , Lazy evaluation
• Function composition
– E.g. collection.filter { x -> x > 5}.map{ x -> x * x}
– Data1 => function1 => data2 => functions2 => data3 => ...
– The only requirement is F1’s output type should match to F2’s input type
– Solution : Curried functions , Monads
• No shared mutable state
– Pure functions don’t change state
– Functions without side-effects (mutability)
– Functions are Deterministic. Data is immutable.
Imperative Programming
Functional Programming
Easy to change implementation.
With FP, Internal Iteration implementation can be changed: forEach => parallel forEach
1,000,000 users?
Functional Reactive Programming
FRP is all about effectively processing event streams without explicitly managing state.
Modern code
var a = 10;
var b <= a + 1;
a = 20;
Assert.AreEqual(21, b);
Ancient code
var a = 10;
var b = a + 1;
a = 11;
console.log(b);
“We don't assign variables, we express them, and they don't represent discrete
values, they represent a value that changes over time.”
a = b + c becomes var a = function (b,c) { return b + c }
Imperative Programming output => 11
Relative Programming output => 21
a := b + c ; meant a always equals b plus c, at any
time
Similarities with observer pattern
Observer pattern commonly describes data-flows between whole objects/classes, whereas FRP could
target the members of objects/classes. Observer pattern has limitations like Unpredictable order, Leaking
listeners, Threading issues, Messy State, Compositionality, Accidental recursion etc.,
Similarities with 2-way data binding
Models are updated with manual communication , in FRP they react to events
http://www.reactivemanifesto.org
FRP Terminology
Time-varying Values dynamic/evolving values (values "over time”), a.k.a DataFlow
Variables , e.g., temperature , vehicle speed, Stock symbol etc.
Signals/Events ‘Changing a value’ is an Event. Anything that happens multiple times
and/or that might be triggered at random intervals should be implemented as Signals/Events.
Event Streams are sources of events. Streams of timed values. These can be mouse
clicks, keyboard events, mouse drag or any other input. Streams are composable. demand-driven
(pull) sampling vs., data-driven (push) evaluation.
Functional Reactive Bindings controlled data binding.
AngularJS team reported that their code ran 20-40 times faster than it had previously switching
to Object.observe
typeahead search with FRP
distinct stream guaranteed that events:
1. will be non-empty strings with length
greater than two
2. will not occur too frequently, and
3. will not include duplicates.
This creates an event stream from all keyup
and change events on the given input.
The stream is transformed into a stream of
strings matching the value of the input when
each event occurs.
Then that stream is filtered so that
subscribers to inputs will only receive
events if the value of the input has a length
greater than two.
Promises , Generators and FRP comparison
Service
<news></news>
Model
Promise
Back End
<news></news>
Model
<news></news>
Model
Generator
Observable (FRP)
Promise.then()
• Emit result only once
Generator.next()
• Emit results until the end
• Caller driven execution
Observable.subscribe()
• Results emitted as
and when available
in sequence.
UI Component
Sync & Async APIs with single & multi-valued response
Single Multiple
Sync T getData() Generator<T> getData()
Async Promise<T> getData() Observable<T> getData()
synchronous scalar response Sync: multi-value iterable response, execution deferred to next() call
Async scalar response
Observable supports single value, a sequence of values or
an infinite stream and enable reactive programming model.
FRP is abstracted from source of
concurrency.
It is not opinionated and allows the
implementer to decide.
For example, an Observable API could just
use calling thread to synchronously
execute and respond...
or it could use a thread-pool to do the
work asynchronously and callback with
that thread....
or it could use multiple threads, each thread
calling back via onNext(T) when the value is
ready....
Your choice of concurrency implantation
or it could use actor pattern instead of a
thread-pool...
Do work asynchronously on an Actor (or
multiple Actors)
... or NIO with even-loop...
Do network access asynchronously using
NIO and perform callback on Event Loop.
... or thread-pool/actor that does the work but
then performs the callback via an event-loop
so the thread-pool/actor is tuned for IO and
event-loop for CPU.
All of those different implementation choices are possible
without changing the signature of the method and
without the calling code changing their behavior or how
they interact with or compose responses
Asynchronous Observable with Single value Synchronous Observable with Multiple value
Asynchronous Observable with Multiple value
Client: Subscribe to Asynchronous Observer
Event Streams
Work with Event Stream instead of single events
Comprisable Functions =>
Combining via Merge
Combining via Zip , Error Handling
Composition Example
Composition Example
Return a single Map of transformed and combined data from 4 asynchronous calls
Web components are ...
Custom Elements
Decorators
<Template>
HTML Imports
Object.observe
Shadow DOM
Polymer, the Web Components polyfill
DOM Mutation Observers
Pointer Events
Web Animations
Web Components are...
The Web Components API is a collection of four different specs
from the W3C designed to work together:
• HTML Templates
– inert chunks of DOM activated when needed. <template>
• Custom Elements,
– create new HTML elements, extend existing DOM objects.
– Give them an API with properties and methods.
• Shadow DOM
– style & DOM encapsulation
• HTML Imports
– bundle and distribute common HTML/CSS/JS (e.g. components)
Custom Elements
1. New standards to create custom html elements.
2. Encapsulation HTML and CSS into ShadowDOM.
3. Mimic built-in elements as closely as possible. DOM
API treats custom elements as first-class
(e.g. appendChild accepts custom elements).
4. Elements can be inserted using either HTML markup
or scripts.
5. Lets designers use custom elements like HTML
6. Think of HealthCare UI Components that
complement to HBS Services. Which can be used as UI
building blocks to build HealthCare WebApps
Shadow DOM
Shadow DOM allows you to stuff a bunch of complex junk out of sight.
Create Your Own HTML tags
<polymer-ui-accordion>
<polymer-ui-animated-pages>
<polymer-ui-overlay>
<polymer-ui-card>
<polymer-ui-sidebar-menu>
<polymer-ui-tabs>
<polymer-ui-toggle-button>
<polymer-ui-theme-aware>
Using Custom Elements is Easy
WebApp Designer
DI vs. AMD
AngularJS inject Instances
RequireJS inject Classes
• Developers use RequireJS to asynchronously load
JavaScript and establish package/import dependencies.
• Think of AngularJS DI as injecting instances and RequireJS
AMD DI as injecting Classes or constructors
• Avoiding Scope Pollution
• ES6 Modules ~= Java Packages
• Watch out for Cyclic dependencies
• DI 2.0 : Hieratical Injectors , singleton, prototype scopes
DI 2.0 with JavaScript Annotations
SPA Navigation
• Navigating deep-links with HTML5 History API and UI Router
• UI driven back navigation for SPA
• undo , redo , work-in-progress
• 401/403: Pause for login, and show the destination page on success
Synchronized Cache
• Backend: Hibernate 2nd level cache
– All shared domain instances + selective queries are cached
– RESTful API bulk pagination with maxResults and offset
• Frontend: HTTP Cache
– RESTful API with Last-Modified &If-Modified-Since support
– RESTful API with Etag & If-None-Match support
• Frontend: angular-cache
– Sensible cache configuration for each cached object type,
managed at angular service level.
– ngTable module for local pagination, sort, filter
– Client can specify which fields should be included in results
Single Page Applications with AngularJS 2.0
Backend RESTful API
Item List
• http://localhost:8080/Batch/drugs.json?max=2
• http://localhost:8080/Batch/drugs.json?max=2&offset=100
• http://localhost:8080/Batch/drugs.json?max=2&offset=100&fields=ndc,id
Item Search
• http://localhost:8080/Batch/drugs/search?format=xml&labelerName=ON
VATEC&productName=AKIN
• http://localhost:8080/Batch/drugs/search?format=json&labelerName=ON
VATEC&productName=AKIN&max=2
Item Details
• http://localhost:8080/Batch/drugs/1?format=json
• http://localhost:8080/Batch/drugs/1.json?fields=ndc,id
• http://localhost:8080/Batch/drugs/1.json?fields=ndc,id,recordTypeE
Single Page Applications with AngularJS 2.0
Single Page Applications with AngularJS 2.0
SPA Authentication and Authorization
• Authentication - Show login Dialog
– Http Interceptor - when server return 401 (just-in-time)
– When user clicks login link in the header.
– Session Expiration - when server return 419/440
– Redirect to target view after successfully login.
• Permission based Access Control
– Restrict UI visibility - Showing or hiding part of the
screens based on the user permissions.
– Routing - When the user access a route that he
doesn’t have permission, will show error message.
– Http Interceptor - when server return 403, emit event
oAuth for securing backend APIs
oAuth liberate from last
mile statelessness for your
backend components
Source: http://alvarosanchez.github.io/grails-spring-security-rest/docs/index.html
Double oAuth: managing 3rd party issued tokens
Source: http://alvarosanchez.github.io/grails-spring-security-rest/docs/index.html
Anatomy of the E2E App
CORS
Solution : http://software.dzhuvinov.com/cors-filter.html
The future of the web is cross-domain, not same-origin
What's Next
• Real-Time REST Services
• Streaming UI Components
– WebSockets, WebRTC, polyfill: SockJS
• Utilizing Backend-as-a-Services(BaaS)
– Firebase, cloud storage, notifications, social networks
• Client-side ORM for REST API & API Orchestration
– Mashup and Consume REST API using SQL like DSL(ql.io)
• Resiliency Annotations for JavaScript/ES7
– Circuit Breaker
– Fallback
– Governor (rate-limit, concurrency control)
Resources
• ECMAScript 6
– http://chimera.labs.oreilly.com/books/1234000001623/ch01.html
– https://github.com/google/traceur-compiler/wiki/LanguageFeatures
– https://www.promisejs.org/
– http://slides.com/thomasboyt/promises-102
– http://tobyho.com/2013/06/16/what-are-generators/
– https://medium.com/code-adventures/174f1fe66127
– http://slides.com/gerreddillon/es6-generators/fullscreen#/
• Brower support Check
– http://www.chromestatus.com/features
• Testing
– Protractor http://ramonvictor.github.io/protractor/slides/#/
• Gulp
– http://markdalgleish.github.io/presentation-build-wars-gulp-vs-grunt/
• Modularity Matters
– http://blog.safaribooksonline.com/2014/03/27/13-step-guide-angularjs-modularization/
– http://thesassway.com/beginner/how-to-structure-a-sass-project
– http://smacss.com/
• Web Components
– http://customelements.io/
– http://html5-demos.appspot.com/shadowdom-visualizer
• Functional Reactive Programming
– http://latentflip.com/bacon-talk-realtimeconfeu/#
– Functors, Applicatives, And Monads In Pictures http://adit.io/posts/2013-04-17-functors,_applicatives,_and_monads_in_pictures.html
• Securing Single Page Apps and REST Services
– http://www.jamesward.com/2013/05/13/securing-single-page-apps-and-rest-services
– http://alvarosanchez.github.io/grails-spring-security-rest/docs/index.html
1 of 66

Recommended

Tech Webinar: Angular 2, Introduction to a new framework by
Tech Webinar: Angular 2, Introduction to a new frameworkTech Webinar: Angular 2, Introduction to a new framework
Tech Webinar: Angular 2, Introduction to a new frameworkCodemotion
1.8K views48 slides
Overview of the AngularJS framework by
Overview of the AngularJS framework Overview of the AngularJS framework
Overview of the AngularJS framework Yakov Fain
3K views58 slides
Angular2 Development for Java developers by
Angular2 Development for Java developersAngular2 Development for Java developers
Angular2 Development for Java developersYakov Fain
3.9K views66 slides
Angular1x and Angular 2 for Beginners by
Angular1x and Angular 2 for BeginnersAngular1x and Angular 2 for Beginners
Angular1x and Angular 2 for BeginnersOswald Campesato
1.8K views70 slides
Introduction to Angular 2 by
Introduction to Angular 2Introduction to Angular 2
Introduction to Angular 2Knoldus Inc.
22.4K views25 slides
AngularJS with RequireJS by
AngularJS with RequireJSAngularJS with RequireJS
AngularJS with RequireJSJohannes Weber
8.3K views21 slides

More Related Content

What's hot

Angular 2 overview by
Angular 2 overviewAngular 2 overview
Angular 2 overviewJesse Warden
3.8K views77 slides
Angular 2 for Java Developers by
Angular 2 for Java DevelopersAngular 2 for Java Developers
Angular 2 for Java DevelopersYakov Fain
25.9K views57 slides
AngularJS application architecture by
AngularJS application architectureAngularJS application architecture
AngularJS application architectureGabriele Falace
12.7K views29 slides
AngularJS - Architecture decisions in a large project  by
AngularJS - Architecture decisionsin a large project AngularJS - Architecture decisionsin a large project 
AngularJS - Architecture decisions in a large project Elad Hirsch
3.5K views71 slides
Angular2 for Beginners by
Angular2 for BeginnersAngular2 for Beginners
Angular2 for BeginnersOswald Campesato
1K views45 slides
Speed up your Web applications with HTML5 WebSockets by
Speed up your Web applications with HTML5 WebSocketsSpeed up your Web applications with HTML5 WebSockets
Speed up your Web applications with HTML5 WebSocketsYakov Fain
3.2K views40 slides

What's hot(20)

Angular 2 overview by Jesse Warden
Angular 2 overviewAngular 2 overview
Angular 2 overview
Jesse Warden3.8K views
Angular 2 for Java Developers by Yakov Fain
Angular 2 for Java DevelopersAngular 2 for Java Developers
Angular 2 for Java Developers
Yakov Fain25.9K views
AngularJS application architecture by Gabriele Falace
AngularJS application architectureAngularJS application architecture
AngularJS application architecture
Gabriele Falace12.7K views
AngularJS - Architecture decisions in a large project  by Elad Hirsch
AngularJS - Architecture decisionsin a large project AngularJS - Architecture decisionsin a large project 
AngularJS - Architecture decisions in a large project 
Elad Hirsch3.5K views
Speed up your Web applications with HTML5 WebSockets by Yakov Fain
Speed up your Web applications with HTML5 WebSocketsSpeed up your Web applications with HTML5 WebSockets
Speed up your Web applications with HTML5 WebSockets
Yakov Fain3.2K views
Angular2 intro by Shawn McKay
Angular2 introAngular2 intro
Angular2 intro
Shawn McKay1.8K views
Angular 2: core concepts by Codemotion
Angular 2: core conceptsAngular 2: core concepts
Angular 2: core concepts
Codemotion1.2K views
Exploring Angular 2 - Episode 1 by Ahmed Moawad
Exploring Angular 2 - Episode 1Exploring Angular 2 - Episode 1
Exploring Angular 2 - Episode 1
Ahmed Moawad681 views
Intro to JavaScript by Yakov Fain
Intro to JavaScriptIntro to JavaScript
Intro to JavaScript
Yakov Fain2K views
Angular Weekend by Troy Miles
Angular WeekendAngular Weekend
Angular Weekend
Troy Miles1.2K views
AngularJs presentation by Phan Tuan
AngularJs presentation AngularJs presentation
AngularJs presentation
Phan Tuan1.4K views
What’s new in angular 2 by Ran Wahle
What’s new in angular 2What’s new in angular 2
What’s new in angular 2
Ran Wahle1.4K views
Front end development with Angular JS by Bipin
Front end development with Angular JSFront end development with Angular JS
Front end development with Angular JS
Bipin861 views
AngularJS - What is it & Why is it awesome ? (with demos) by Gary Arora
AngularJS - What is it & Why is it awesome ? (with demos)AngularJS - What is it & Why is it awesome ? (with demos)
AngularJS - What is it & Why is it awesome ? (with demos)
Gary Arora37.3K views
AngularJS 101 - Everything you need to know to get started by Stéphane Bégaudeau
AngularJS 101 - Everything you need to know to get startedAngularJS 101 - Everything you need to know to get started
AngularJS 101 - Everything you need to know to get started
Stéphane Bégaudeau55.5K views

Viewers also liked

Measuring the Performance of Single Page Applications by
Measuring the Performance of Single Page ApplicationsMeasuring the Performance of Single Page Applications
Measuring the Performance of Single Page ApplicationsNicholas Jansma
16.7K views74 slides
AngularJS 2.0 by
AngularJS 2.0AngularJS 2.0
AngularJS 2.0Boyan Mihaylov
2.9K views18 slides
Angular jsの継続的なバージョンアップ by
Angular jsの継続的なバージョンアップAngular jsの継続的なバージョンアップ
Angular jsの継続的なバージョンアップKazuyoshi Tsuchiya
13.5K views46 slides
Javaな人が気を付けるべきJavaScriptコーディングスタイル by
Javaな人が気を付けるべきJavaScriptコーディングスタイルJavaな人が気を付けるべきJavaScriptコーディングスタイル
Javaな人が気を付けるべきJavaScriptコーディングスタイルMaaya Ishida
919 views62 slides
jQueryの先に行こう!最先端のWeb開発トレンドを学ぶ by
jQueryの先に行こう!最先端のWeb開発トレンドを学ぶjQueryの先に行こう!最先端のWeb開発トレンドを学ぶ
jQueryの先に行こう!最先端のWeb開発トレンドを学ぶShumpei Shiraishi
4.3K views80 slides
Understanding User Experience Design_V2 by
Understanding User Experience Design_V2Understanding User Experience Design_V2
Understanding User Experience Design_V2Frank Chen
204 views21 slides

Viewers also liked(20)

Measuring the Performance of Single Page Applications by Nicholas Jansma
Measuring the Performance of Single Page ApplicationsMeasuring the Performance of Single Page Applications
Measuring the Performance of Single Page Applications
Nicholas Jansma16.7K views
Angular jsの継続的なバージョンアップ by Kazuyoshi Tsuchiya
Angular jsの継続的なバージョンアップAngular jsの継続的なバージョンアップ
Angular jsの継続的なバージョンアップ
Kazuyoshi Tsuchiya13.5K views
Javaな人が気を付けるべきJavaScriptコーディングスタイル by Maaya Ishida
Javaな人が気を付けるべきJavaScriptコーディングスタイルJavaな人が気を付けるべきJavaScriptコーディングスタイル
Javaな人が気を付けるべきJavaScriptコーディングスタイル
Maaya Ishida919 views
jQueryの先に行こう!最先端のWeb開発トレンドを学ぶ by Shumpei Shiraishi
jQueryの先に行こう!最先端のWeb開発トレンドを学ぶjQueryの先に行こう!最先端のWeb開発トレンドを学ぶ
jQueryの先に行こう!最先端のWeb開発トレンドを学ぶ
Shumpei Shiraishi4.3K views
Understanding User Experience Design_V2 by Frank Chen
Understanding User Experience Design_V2Understanding User Experience Design_V2
Understanding User Experience Design_V2
Frank Chen204 views
Intro to IA/IxD/UXD in the agency world by Karri Ojanen
Intro to IA/IxD/UXD in the agency worldIntro to IA/IxD/UXD in the agency world
Intro to IA/IxD/UXD in the agency world
Karri Ojanen1.9K views
Building Scalable Aggregation Systems by Jared Winick
Building Scalable Aggregation SystemsBuilding Scalable Aggregation Systems
Building Scalable Aggregation Systems
Jared Winick2.4K views
Building Evented Single Page Applications by Steve Smith
Building Evented Single Page ApplicationsBuilding Evented Single Page Applications
Building Evented Single Page Applications
Steve Smith870 views
Angular 2.0 Views by Eyal Vardi
Angular 2.0 ViewsAngular 2.0 Views
Angular 2.0 Views
Eyal Vardi1.8K views
Reactive programming by Jianbin LIN
Reactive programmingReactive programming
Reactive programming
Jianbin LIN600 views
Reactive web applications by Juan Sandoval
Reactive web applicationsReactive web applications
Reactive web applications
Juan Sandoval339 views
AngularJS Routing by Eyal Vardi
AngularJS RoutingAngularJS Routing
AngularJS Routing
Eyal Vardi10.1K views
The New UI - Staying Strong with Flexbox, SASS, and {{Mustache.js}} by Eric Carlisle
The New UI - Staying Strong with Flexbox, SASS, and {{Mustache.js}}The New UI - Staying Strong with Flexbox, SASS, and {{Mustache.js}}
The New UI - Staying Strong with Flexbox, SASS, and {{Mustache.js}}
Eric Carlisle2.6K views
Single-Page Application Design Principles 101 by Jollen Chen
Single-Page Application Design Principles 101Single-Page Application Design Principles 101
Single-Page Application Design Principles 101
Jollen Chen3.8K views
Can Single Page Applications Deliver a World-Class Web UX? by UXPA International
Can Single Page Applications Deliver a World-Class Web UX?Can Single Page Applications Deliver a World-Class Web UX?
Can Single Page Applications Deliver a World-Class Web UX?
Modern app programming with RxJava and Eclipse Vert.x by Thomas Segismont
Modern app programming with RxJava and Eclipse Vert.xModern app programming with RxJava and Eclipse Vert.x
Modern app programming with RxJava and Eclipse Vert.x
Thomas Segismont3K views
Securing Single-Page Applications with OAuth 2.0 by Prabath Siriwardena
Securing Single-Page Applications with OAuth 2.0Securing Single-Page Applications with OAuth 2.0
Securing Single-Page Applications with OAuth 2.0
Prabath Siriwardena5.2K views

Similar to Single Page Applications with AngularJS 2.0

Velocity 2018 preetha appan final by
Velocity 2018   preetha appan finalVelocity 2018   preetha appan final
Velocity 2018 preetha appan finalpreethaappan
118 views70 slides
SamzaSQL QCon'16 presentation by
SamzaSQL QCon'16 presentationSamzaSQL QCon'16 presentation
SamzaSQL QCon'16 presentationYi Pan
1.9K views50 slides
Performance measurement methodology — Maksym Pugach | Elixir Evening Club 3 by
Performance measurement methodology — Maksym Pugach | Elixir Evening Club 3Performance measurement methodology — Maksym Pugach | Elixir Evening Club 3
Performance measurement methodology — Maksym Pugach | Elixir Evening Club 3Elixir Club
489 views26 slides
Developing Microservices using Spring - Beginner's Guide by
Developing Microservices using Spring - Beginner's GuideDeveloping Microservices using Spring - Beginner's Guide
Developing Microservices using Spring - Beginner's GuideMohanraj Thirumoorthy
1.2K views24 slides
Spark Summit EU talk by Nick Pentreath by
Spark Summit EU talk by Nick PentreathSpark Summit EU talk by Nick Pentreath
Spark Summit EU talk by Nick PentreathSpark Summit
1.3K views31 slides
Camunda BPM 7.2: Performance and Scalability (English) by
Camunda BPM 7.2: Performance and Scalability (English)Camunda BPM 7.2: Performance and Scalability (English)
Camunda BPM 7.2: Performance and Scalability (English)camunda services GmbH
9.9K views56 slides

Similar to Single Page Applications with AngularJS 2.0 (20)

Velocity 2018 preetha appan final by preethaappan
Velocity 2018   preetha appan finalVelocity 2018   preetha appan final
Velocity 2018 preetha appan final
preethaappan118 views
SamzaSQL QCon'16 presentation by Yi Pan
SamzaSQL QCon'16 presentationSamzaSQL QCon'16 presentation
SamzaSQL QCon'16 presentation
Yi Pan1.9K views
Performance measurement methodology — Maksym Pugach | Elixir Evening Club 3 by Elixir Club
Performance measurement methodology — Maksym Pugach | Elixir Evening Club 3Performance measurement methodology — Maksym Pugach | Elixir Evening Club 3
Performance measurement methodology — Maksym Pugach | Elixir Evening Club 3
Elixir Club489 views
Developing Microservices using Spring - Beginner's Guide by Mohanraj Thirumoorthy
Developing Microservices using Spring - Beginner's GuideDeveloping Microservices using Spring - Beginner's Guide
Developing Microservices using Spring - Beginner's Guide
Spark Summit EU talk by Nick Pentreath by Spark Summit
Spark Summit EU talk by Nick PentreathSpark Summit EU talk by Nick Pentreath
Spark Summit EU talk by Nick Pentreath
Spark Summit1.3K views
Camunda BPM 7.2: Performance and Scalability (English) by camunda services GmbH
Camunda BPM 7.2: Performance and Scalability (English)Camunda BPM 7.2: Performance and Scalability (English)
Camunda BPM 7.2: Performance and Scalability (English)
6 tips for improving ruby performance by Engine Yard
6 tips for improving ruby performance6 tips for improving ruby performance
6 tips for improving ruby performance
Engine Yard6.6K views
2011-02-03 LA RubyConf Rails3 TDD Workshop by Wolfram Arnold
2011-02-03 LA RubyConf Rails3 TDD Workshop2011-02-03 LA RubyConf Rails3 TDD Workshop
2011-02-03 LA RubyConf Rails3 TDD Workshop
Wolfram Arnold708 views
Tooling for Machine Learning: AWS Products, Open Source Tools, and DevOps Pra... by SQUADEX
Tooling for Machine Learning: AWS Products, Open Source Tools, and DevOps Pra...Tooling for Machine Learning: AWS Products, Open Source Tools, and DevOps Pra...
Tooling for Machine Learning: AWS Products, Open Source Tools, and DevOps Pra...
SQUADEX761 views
Flink Forward SF 2017: Malo Deniélou - No shard left behind: Dynamic work re... by Flink Forward
Flink Forward SF 2017: Malo Deniélou -  No shard left behind: Dynamic work re...Flink Forward SF 2017: Malo Deniélou -  No shard left behind: Dynamic work re...
Flink Forward SF 2017: Malo Deniélou - No shard left behind: Dynamic work re...
Flink Forward267 views
Dr Elephant: LinkedIn's Self-Service System for Detecting and Treating Hadoop... by DataWorks Summit
Dr Elephant: LinkedIn's Self-Service System for Detecting and Treating Hadoop...Dr Elephant: LinkedIn's Self-Service System for Detecting and Treating Hadoop...
Dr Elephant: LinkedIn's Self-Service System for Detecting and Treating Hadoop...
DataWorks Summit5.2K views
Angular - Improve Runtime performance 2019 by Eliran Eliassy
Angular - Improve Runtime performance 2019Angular - Improve Runtime performance 2019
Angular - Improve Runtime performance 2019
Eliran Eliassy748 views
Dask and Machine Learning Models in Production - PyColorado 2019 by William Cox
Dask and Machine Learning Models in Production - PyColorado 2019Dask and Machine Learning Models in Production - PyColorado 2019
Dask and Machine Learning Models in Production - PyColorado 2019
William Cox1.8K views
End to end testing Single Page Apps & APIs with Cucumber.js and Puppeteer (Em... by Paul Jensen
End to end testing Single Page Apps & APIs with Cucumber.js and Puppeteer (Em...End to end testing Single Page Apps & APIs with Cucumber.js and Puppeteer (Em...
End to end testing Single Page Apps & APIs with Cucumber.js and Puppeteer (Em...
Paul Jensen679 views
Performance Test Automation With Gatling by Knoldus Inc.
Performance Test Automation  With GatlingPerformance Test Automation  With Gatling
Performance Test Automation With Gatling
Knoldus Inc.1.8K views
NetflixOSS Open House Lightning talks by Ruslan Meshenberg
NetflixOSS Open House Lightning talksNetflixOSS Open House Lightning talks
NetflixOSS Open House Lightning talks
Ruslan Meshenberg136.3K views

Recently uploaded

Compare the flora and fauna of Kerala and Chhattisgarh ( Charttabulation) by
 Compare the flora and fauna of Kerala and Chhattisgarh ( Charttabulation) Compare the flora and fauna of Kerala and Chhattisgarh ( Charttabulation)
Compare the flora and fauna of Kerala and Chhattisgarh ( Charttabulation)AnshulDewangan3
316 views12 slides
Class 10 English notes 23-24.pptx by
Class 10 English notes 23-24.pptxClass 10 English notes 23-24.pptx
Class 10 English notes 23-24.pptxTARIQ KHAN
107 views53 slides
231112 (WR) v1 ChatGPT OEB 2023.pdf by
231112 (WR) v1  ChatGPT OEB 2023.pdf231112 (WR) v1  ChatGPT OEB 2023.pdf
231112 (WR) v1 ChatGPT OEB 2023.pdfWilfredRubens.com
144 views21 slides
ICS3211_lecture 08_2023.pdf by
ICS3211_lecture 08_2023.pdfICS3211_lecture 08_2023.pdf
ICS3211_lecture 08_2023.pdfVanessa Camilleri
103 views30 slides
Psychology KS5 by
Psychology KS5Psychology KS5
Psychology KS5WestHatch
77 views5 slides

Recently uploaded(20)

Compare the flora and fauna of Kerala and Chhattisgarh ( Charttabulation) by AnshulDewangan3
 Compare the flora and fauna of Kerala and Chhattisgarh ( Charttabulation) Compare the flora and fauna of Kerala and Chhattisgarh ( Charttabulation)
Compare the flora and fauna of Kerala and Chhattisgarh ( Charttabulation)
AnshulDewangan3316 views
Class 10 English notes 23-24.pptx by TARIQ KHAN
Class 10 English notes 23-24.pptxClass 10 English notes 23-24.pptx
Class 10 English notes 23-24.pptx
TARIQ KHAN107 views
Psychology KS5 by WestHatch
Psychology KS5Psychology KS5
Psychology KS5
WestHatch77 views
Scope of Biochemistry.pptx by shoba shoba
Scope of Biochemistry.pptxScope of Biochemistry.pptx
Scope of Biochemistry.pptx
shoba shoba124 views
The basics - information, data, technology and systems.pdf by JonathanCovena1
The basics - information, data, technology and systems.pdfThe basics - information, data, technology and systems.pdf
The basics - information, data, technology and systems.pdf
JonathanCovena188 views
Solar System and Galaxies.pptx by DrHafizKosar
Solar System and Galaxies.pptxSolar System and Galaxies.pptx
Solar System and Galaxies.pptx
DrHafizKosar85 views
EIT-Digital_Spohrer_AI_Intro 20231128 v1.pptx by ISSIP
EIT-Digital_Spohrer_AI_Intro 20231128 v1.pptxEIT-Digital_Spohrer_AI_Intro 20231128 v1.pptx
EIT-Digital_Spohrer_AI_Intro 20231128 v1.pptx
ISSIP317 views
Classification of crude drugs.pptx by GayatriPatra14
Classification of crude drugs.pptxClassification of crude drugs.pptx
Classification of crude drugs.pptx
GayatriPatra1477 views
Drama KS5 Breakdown by WestHatch
Drama KS5 BreakdownDrama KS5 Breakdown
Drama KS5 Breakdown
WestHatch71 views
Class 10 English lesson plans by TARIQ KHAN
Class 10 English  lesson plansClass 10 English  lesson plans
Class 10 English lesson plans
TARIQ KHAN257 views
Ch. 7 Political Participation and Elections.pptx by Rommel Regala
Ch. 7 Political Participation and Elections.pptxCh. 7 Political Participation and Elections.pptx
Ch. 7 Political Participation and Elections.pptx
Rommel Regala72 views
Structure and Functions of Cell.pdf by Nithya Murugan
Structure and Functions of Cell.pdfStructure and Functions of Cell.pdf
Structure and Functions of Cell.pdf
Nithya Murugan368 views
OEB 2023 Co-learning To Speed Up AI Implementation in Courses.pptx by Inge de Waard
OEB 2023 Co-learning To Speed Up AI Implementation in Courses.pptxOEB 2023 Co-learning To Speed Up AI Implementation in Courses.pptx
OEB 2023 Co-learning To Speed Up AI Implementation in Courses.pptx
Inge de Waard167 views

Single Page Applications with AngularJS 2.0

  • 1. Single Page Applications 2.0 Push the limits of what’s possible on the web
  • 2. New Topics • Tool Chain, Code Organization • Asset pipeline hooks • Programmable CSS with SASS and Bourbon • Transpile ES6  ES5 • ES6/ES7 with Angular • AMD with Angular • DI 2.0 with Angular • HTML5 Custom Elements • Functional Reactive Programming with Angular • NG- Patterns : Logging, Security, Resiliency, Cache
  • 4. Gulp - Task Runner • The streaming build system. No more temp files. • Gulp replace Grunt. – Install: npm install -g generator-gulp-angular – Run: yo gulp-angular [app-name] – Run gulp for building and gulp watch for preview gulpfile.js
  • 5. Gulp and its NPM packages • Built-in preview server with LiveReload, file watcher • CSS Pre-processing : SASS, Bourbon Mixins • CSS Autoprefixing : add vendor prefixes • JSHinting, CSSLinting : lint your scripts, CSS • JS Transpilers: ES6  ES5 • Awesome Image Optimization, WebP • AMD/RequireJS Support • Concatenation/Optimization, Minification, uglify • Automatically wire-up dependencies installed with Bower (when gulp watch or gulp wiredep)
  • 8. Code Organization • Adopt De Facto Standards – Yeomen generated project structure – Rapid prototyping using scaffolding generators • Modularity: Organize your files by Feature not by Type – Modules are independent WebApp functionality that developers can work in parallel – Isolate complexity into separate pluggable modules – In an AngularJS context, modularization is organization by function instead of type. • Everything that gets deployed is in the app directory. • Everything outside of the app directory is for development
  • 9. Compose Apps by assembling smaller modules
  • 10. Organize Files : by Feature, Not by Type Common/ elements/ myElementTemplate.html MyElement.js services/ i18nService.js filters/ i18nFilter.js i18b/ en_EN.json de_DE.json Index.js orders/ elements/ tableTemplate.html TableElement.js table.css services/ OrderService.js index.js home/ controllers/ HomeController.js LoginController.js services/ UserService.js AuthenticationService.js i18b/ en_EN.json de_DE.json index.js index.js ../views/ home/ home.html orders/ order.html order.details.html
  • 11. Scalable and Modular layout for stylesheets/ | |-- admin/ # Admin sub-project | |-- modules/ | |-- partials/ | `-- _base.scss | |-- account/ # Account sub-project | |-- modules/ | |-- partials/ | `-- _base.scss | |-- site/ # Site sub-project | |-- modules/ | |-- partials/ | `-- _base.scss | |-- vendor/ # CSS or Sass from other projects | |-- _colorpicker-1.1.scss # in Bower case, under bower_components | |-- _jquery.ui.core-1.9.1.scss | ... | |-- admin.scss # Primary stylesheets for each sub-project |-- account.scss |-- _variables.scss `-- site.scss Write leaner, programmable, and maintainable CSS with SASS & Bourbon
  • 12. AMD with Angular Components Modules Root Module Bootstrap Config Config.js Bootstrap.js index.js Home Index.js routes.js Controllers Services Elements Account Index.js routes.js Controllers Services Elements Common Index.js routes.js Controllers Services Elements Dashboard Index.js routes.js Controllers Services Elements
  • 14. Testability Why do you need to write tests? – Because you’re not Chuck Norris. Unit Testing Karma: Spectacular Test Runner using real browsers! – Jasmine: behavior-driven development framework for testing JavaScript code. – Mocha: Simple, flexible JavaScript test framework. PhantomJS: Headless Testing Integration Testing – Protractor: AngularJS E2E Testing Framework gulp test command transpile ES6 tests and perform all unit and integration tests User story: “As a user, when I login to my app, I am taken to the dashboard page.”
  • 15. ECMAScript 6.0 You Can’t Afford to Avoid ES6 Author In ES6, Transpile To ES5 As A Build-step: Gulp Workflow
  • 16. Traceur & Polyfills Traceur and Shim/Polyfill makes it possible to use tomorrows technology now! – Traceur is a JavaScript.next  JavaScript.now compiler – “A polyfill is a piece of code (or plugin) that provides the technology that you, the developer, expect the browser to provide natively. Flattening the API landscape if you will.” ( from Remy Sharp blog) Traceur provide ES6 that are not available in any browser yet. Polyfill provide HTML5/ES6 features that are not available in some of the browsers yet.
  • 17. ES6 Goodies • Modules, Classes, Typed, Traits • Generator, Promises, Proxies • Closures / Fat Arrow Functions • Let, Const, Private scope and Block Functions • Destructuring, For-Of and Array Comprehensions • Spread Operator, Rest Parameter, and Default Arguments • Template Strings, string interpolation • Collections : Set, Map, Weak Set/Map, Binary Data • ES7 Object.observe , async/await functions
  • 19. Promises Promises are useful when you want to represent the outcome of an action or a value that will be available at some future time. – It is an easy way to avoid writing the Pyramid of Doom – Function return a promise - no more callback parameter – A promise represents an eventual outcome – Promises can be pending, fulfilled or rejected – they are only resolved once; – Guaranteed to always be async. – Promises can be chained. Re-tryable – Promises as first-class objects – “then-able” objects. then() method returns another promise and you can return data from the callback to the next promise in the chain. – A deferred is an object representing work that is not yet done and a promise is an object representing a value that is not yet known. Promise Combinators: Promise.all([p1,p2,p3]) , Promise.race([p1,p2,p3]) , Promise.any([p1,p2,p3])
  • 21. Promises fix callback hell of async code
  • 23. Promise Chaining Asynchronous Control Flow with Promises Promises are a replacement for Callbacks to help you deal with composition of multiple async operations while also making error handling simpler in some cases.
  • 24. What's the Big Deal with Generators? "First-class coroutines, represented as objects encapsulating suspended execution contexts (i.e., function activations)”  Allows suspension of a function's execution until resolved - everything else outside of that execution continues. Higher-order functions  Uses a yield statement instead of a return to report values.  The essence of generator is controlling the suspension of code execution. Caller control execution of code in Generator function. Use Cases • Infinite iterator : Good for representing infinite sequences. Generator return iterators. • Non-blocking I/O : When we don't yield execution, we're blocking. • Demand-driven: functions can interactively yield partial results as soon as available. • Lazy Sequences: We can rewrite lazy version of Underscore.js using Generators. Since filter and map return generators, nothing happens until reduce. You can get benefits of declarative functional data manipulation without the performance and memory downsides of intermediate arrays. • Run-to-completion(RTC) is a scheduling model in which each task runs until it either finishes, or explicitly yields control back to the scheduler. • Flow Control: you can actually pass data back in to the generator, causing yield to either return a value or throw an exception inside the generator body. • Synchronously looking Asynchronous code: “Async functions are a thin sugar over generators and a spawn function which converts generators into promise objects”
  • 25. Generators Use case Scenarios This is a big deal: generators finally provide us with a pseudo-synchronous syntax that doesn't break run-to-completion semantics, doesn't require transpiling, and doesn't require callbacks. Basic Examples Control Flow Parallel Loops
  • 26. Generators makes it possible write async code that looks like synchronous
  • 27. ES7 async / await functions
  • 28. AOP in JavaScript • ES6 Proxies and Angular Decorators enable augmenting new behaviors to existing JS Objects and classes at runtime. • Can be used along with Traceur’s Annotations (ES6+) to add cross-cutting concerns by scanning annotations during application bootstrap process. • Angular 2.0 Dependency Injection will adopt this approach. • Retry aspect has been implemented using this technique in SPA Starter Kit.
  • 30. Functional Programming What is FP? A style which utilizes HOFs and minimize side effects. Why FP? Parallelization , Concurrency , Lazy evaluation • Function composition – E.g. collection.filter { x -> x > 5}.map{ x -> x * x} – Data1 => function1 => data2 => functions2 => data3 => ... – The only requirement is F1’s output type should match to F2’s input type – Solution : Curried functions , Monads • No shared mutable state – Pure functions don’t change state – Functions without side-effects (mutability) – Functions are Deterministic. Data is immutable. Imperative Programming Functional Programming
  • 31. Easy to change implementation. With FP, Internal Iteration implementation can be changed: forEach => parallel forEach 1,000,000 users?
  • 32. Functional Reactive Programming FRP is all about effectively processing event streams without explicitly managing state. Modern code var a = 10; var b <= a + 1; a = 20; Assert.AreEqual(21, b); Ancient code var a = 10; var b = a + 1; a = 11; console.log(b); “We don't assign variables, we express them, and they don't represent discrete values, they represent a value that changes over time.” a = b + c becomes var a = function (b,c) { return b + c } Imperative Programming output => 11 Relative Programming output => 21 a := b + c ; meant a always equals b plus c, at any time Similarities with observer pattern Observer pattern commonly describes data-flows between whole objects/classes, whereas FRP could target the members of objects/classes. Observer pattern has limitations like Unpredictable order, Leaking listeners, Threading issues, Messy State, Compositionality, Accidental recursion etc., Similarities with 2-way data binding Models are updated with manual communication , in FRP they react to events http://www.reactivemanifesto.org
  • 33. FRP Terminology Time-varying Values dynamic/evolving values (values "over time”), a.k.a DataFlow Variables , e.g., temperature , vehicle speed, Stock symbol etc. Signals/Events ‘Changing a value’ is an Event. Anything that happens multiple times and/or that might be triggered at random intervals should be implemented as Signals/Events. Event Streams are sources of events. Streams of timed values. These can be mouse clicks, keyboard events, mouse drag or any other input. Streams are composable. demand-driven (pull) sampling vs., data-driven (push) evaluation. Functional Reactive Bindings controlled data binding. AngularJS team reported that their code ran 20-40 times faster than it had previously switching to Object.observe
  • 34. typeahead search with FRP distinct stream guaranteed that events: 1. will be non-empty strings with length greater than two 2. will not occur too frequently, and 3. will not include duplicates. This creates an event stream from all keyup and change events on the given input. The stream is transformed into a stream of strings matching the value of the input when each event occurs. Then that stream is filtered so that subscribers to inputs will only receive events if the value of the input has a length greater than two.
  • 35. Promises , Generators and FRP comparison Service <news></news> Model Promise Back End <news></news> Model <news></news> Model Generator Observable (FRP) Promise.then() • Emit result only once Generator.next() • Emit results until the end • Caller driven execution Observable.subscribe() • Results emitted as and when available in sequence. UI Component
  • 36. Sync & Async APIs with single & multi-valued response Single Multiple Sync T getData() Generator<T> getData() Async Promise<T> getData() Observable<T> getData() synchronous scalar response Sync: multi-value iterable response, execution deferred to next() call Async scalar response Observable supports single value, a sequence of values or an infinite stream and enable reactive programming model.
  • 37. FRP is abstracted from source of concurrency. It is not opinionated and allows the implementer to decide. For example, an Observable API could just use calling thread to synchronously execute and respond... or it could use a thread-pool to do the work asynchronously and callback with that thread.... or it could use multiple threads, each thread calling back via onNext(T) when the value is ready.... Your choice of concurrency implantation
  • 38. or it could use actor pattern instead of a thread-pool... Do work asynchronously on an Actor (or multiple Actors) ... or NIO with even-loop... Do network access asynchronously using NIO and perform callback on Event Loop. ... or thread-pool/actor that does the work but then performs the callback via an event-loop so the thread-pool/actor is tuned for IO and event-loop for CPU. All of those different implementation choices are possible without changing the signature of the method and without the calling code changing their behavior or how they interact with or compose responses
  • 39. Asynchronous Observable with Single value Synchronous Observable with Multiple value Asynchronous Observable with Multiple value Client: Subscribe to Asynchronous Observer
  • 40. Event Streams Work with Event Stream instead of single events Comprisable Functions =>
  • 42. Combining via Zip , Error Handling
  • 44. Composition Example Return a single Map of transformed and combined data from 4 asynchronous calls
  • 45. Web components are ... Custom Elements Decorators <Template> HTML Imports Object.observe Shadow DOM Polymer, the Web Components polyfill DOM Mutation Observers Pointer Events Web Animations
  • 46. Web Components are... The Web Components API is a collection of four different specs from the W3C designed to work together: • HTML Templates – inert chunks of DOM activated when needed. <template> • Custom Elements, – create new HTML elements, extend existing DOM objects. – Give them an API with properties and methods. • Shadow DOM – style & DOM encapsulation • HTML Imports – bundle and distribute common HTML/CSS/JS (e.g. components)
  • 47. Custom Elements 1. New standards to create custom html elements. 2. Encapsulation HTML and CSS into ShadowDOM. 3. Mimic built-in elements as closely as possible. DOM API treats custom elements as first-class (e.g. appendChild accepts custom elements). 4. Elements can be inserted using either HTML markup or scripts. 5. Lets designers use custom elements like HTML 6. Think of HealthCare UI Components that complement to HBS Services. Which can be used as UI building blocks to build HealthCare WebApps
  • 48. Shadow DOM Shadow DOM allows you to stuff a bunch of complex junk out of sight.
  • 49. Create Your Own HTML tags <polymer-ui-accordion> <polymer-ui-animated-pages> <polymer-ui-overlay> <polymer-ui-card> <polymer-ui-sidebar-menu> <polymer-ui-tabs> <polymer-ui-toggle-button> <polymer-ui-theme-aware>
  • 52. DI vs. AMD AngularJS inject Instances RequireJS inject Classes • Developers use RequireJS to asynchronously load JavaScript and establish package/import dependencies. • Think of AngularJS DI as injecting instances and RequireJS AMD DI as injecting Classes or constructors • Avoiding Scope Pollution • ES6 Modules ~= Java Packages • Watch out for Cyclic dependencies • DI 2.0 : Hieratical Injectors , singleton, prototype scopes
  • 53. DI 2.0 with JavaScript Annotations
  • 54. SPA Navigation • Navigating deep-links with HTML5 History API and UI Router • UI driven back navigation for SPA • undo , redo , work-in-progress • 401/403: Pause for login, and show the destination page on success
  • 55. Synchronized Cache • Backend: Hibernate 2nd level cache – All shared domain instances + selective queries are cached – RESTful API bulk pagination with maxResults and offset • Frontend: HTTP Cache – RESTful API with Last-Modified &If-Modified-Since support – RESTful API with Etag & If-None-Match support • Frontend: angular-cache – Sensible cache configuration for each cached object type, managed at angular service level. – ngTable module for local pagination, sort, filter – Client can specify which fields should be included in results
  • 57. Backend RESTful API Item List • http://localhost:8080/Batch/drugs.json?max=2 • http://localhost:8080/Batch/drugs.json?max=2&offset=100 • http://localhost:8080/Batch/drugs.json?max=2&offset=100&fields=ndc,id Item Search • http://localhost:8080/Batch/drugs/search?format=xml&labelerName=ON VATEC&productName=AKIN • http://localhost:8080/Batch/drugs/search?format=json&labelerName=ON VATEC&productName=AKIN&max=2 Item Details • http://localhost:8080/Batch/drugs/1?format=json • http://localhost:8080/Batch/drugs/1.json?fields=ndc,id • http://localhost:8080/Batch/drugs/1.json?fields=ndc,id,recordTypeE
  • 60. SPA Authentication and Authorization • Authentication - Show login Dialog – Http Interceptor - when server return 401 (just-in-time) – When user clicks login link in the header. – Session Expiration - when server return 419/440 – Redirect to target view after successfully login. • Permission based Access Control – Restrict UI visibility - Showing or hiding part of the screens based on the user permissions. – Routing - When the user access a route that he doesn’t have permission, will show error message. – Http Interceptor - when server return 403, emit event
  • 61. oAuth for securing backend APIs oAuth liberate from last mile statelessness for your backend components Source: http://alvarosanchez.github.io/grails-spring-security-rest/docs/index.html
  • 62. Double oAuth: managing 3rd party issued tokens Source: http://alvarosanchez.github.io/grails-spring-security-rest/docs/index.html
  • 63. Anatomy of the E2E App
  • 64. CORS Solution : http://software.dzhuvinov.com/cors-filter.html The future of the web is cross-domain, not same-origin
  • 65. What's Next • Real-Time REST Services • Streaming UI Components – WebSockets, WebRTC, polyfill: SockJS • Utilizing Backend-as-a-Services(BaaS) – Firebase, cloud storage, notifications, social networks • Client-side ORM for REST API & API Orchestration – Mashup and Consume REST API using SQL like DSL(ql.io) • Resiliency Annotations for JavaScript/ES7 – Circuit Breaker – Fallback – Governor (rate-limit, concurrency control)
  • 66. Resources • ECMAScript 6 – http://chimera.labs.oreilly.com/books/1234000001623/ch01.html – https://github.com/google/traceur-compiler/wiki/LanguageFeatures – https://www.promisejs.org/ – http://slides.com/thomasboyt/promises-102 – http://tobyho.com/2013/06/16/what-are-generators/ – https://medium.com/code-adventures/174f1fe66127 – http://slides.com/gerreddillon/es6-generators/fullscreen#/ • Brower support Check – http://www.chromestatus.com/features • Testing – Protractor http://ramonvictor.github.io/protractor/slides/#/ • Gulp – http://markdalgleish.github.io/presentation-build-wars-gulp-vs-grunt/ • Modularity Matters – http://blog.safaribooksonline.com/2014/03/27/13-step-guide-angularjs-modularization/ – http://thesassway.com/beginner/how-to-structure-a-sass-project – http://smacss.com/ • Web Components – http://customelements.io/ – http://html5-demos.appspot.com/shadowdom-visualizer • Functional Reactive Programming – http://latentflip.com/bacon-talk-realtimeconfeu/# – Functors, Applicatives, And Monads In Pictures http://adit.io/posts/2013-04-17-functors,_applicatives,_and_monads_in_pictures.html • Securing Single Page Apps and REST Services – http://www.jamesward.com/2013/05/13/securing-single-page-apps-and-rest-services – http://alvarosanchez.github.io/grails-spring-security-rest/docs/index.html

Editor's Notes

  1. Functors, Applicatives, And Monads In Pictures - http://adit.io/posts/2013-04-17-functors,_applicatives,_and_monads_in_pictures.html Functors: you apply a function to a wrapped value using fmap or <$> Functors are defined as a function encapsulated in an object. e.g., UnaryPredicate , Comparator The fact that these functions are encapsulated by real objects is also the reason for its greatest benefit. Applicatives: you apply a wrapped function to a wrapped value using <*> or liftA Monads: you apply a function that returns a wrapped value, to a wrapped value using >>= or liftM Java8’s Monads : Options, Maybe Monad is the triple (T, η, μ) where T is the Monad Functor η is the unit function that lifts an ordinary object (a unit) into the Monad functor; and, μ is the join function that takes a composed monad M (M a) and returns the simplified type of the composition, or M a.
  2. https://github.com/PolymerLabs/designer http://www.polymer-project.org/tools/sandbox/
  3. Custom Element boilerplate project https://github.com/webcomponents/element-boilerplate
  4. Pause backed RESTful call on 401, retry paused promise on successful login and show the destination page.