SlideShare a Scribd company logo
REDUX &
ANGULAR 2.0
Nir Kaufman
Nir Kaufman
Head of Angular Development @ 500Tech
- AngularJS evangelist
- International speaker
- Guitar player
*Photoshop
Redux with angular 2 - workshop 2016
Redux with angular 2 - workshop 2016
Redux with angular 2 - workshop 2016
Redux with angular 2 - workshop 2016
THE CHALLENGE
SPA BECOME
INCREASINGLY
COMPLICATED
THERE IS NOTHING
WRONG WITH THE
MVC PATTERN
IF YOU ARE
BUILDING A CRUD
APPLICATION
Redux with angular 2 - workshop 2016
BUT WE ARE
PUSHING THE
ENVELOPE AS MUCH
AS WE CAN
Redux with angular 2 - workshop 2016
MANAGING AN
EVER-CHANGING STATE
IS A HARD TASK
EVERYTHING IS
CONNECTED TO
EVERYTHING
VIEW
VIEW
CONTROLLER
VIEW
CONTROLLER
MODEL MODEL
VIEW
CONTROLLER
MODEL MODEL MODEL
VIEW
CONTROLLER
MODEL MODEL MODEL
MODEL
VIEW
CONTROLLER
MODEL MODEL MODEL MODEL
MODEL
VIEW
CONTROLLER
MODEL
LIBRARY
MODEL MODEL MODEL
MODEL MODEL
VIEW
CONTROLLER
MODEL
LIBRARYLIBRARY
MODEL MODEL MODEL
MODEL MODEL MODEL MODEL
CHANGING SOMETHING
BREAKS SOMETHING
SOMEWHERE
Redux with angular 2 - workshop 2016
ENTER REDUX
https://github.com/nirkaufman/redux-playground
http://tinyurl.com/hq23lsa
PLAY ALONG
REDUX IS A LIBRARY
FOR IMPLEMNETING A
DESIGN PATTERN
REDUX ATTEMPTS TO
MAKE STATE MUTATIONS
PREDICTABLE
INSPIRED BY
FLUX, CQRS &
EVENT SOURCING
REDUX INTREDUCE
THREE PRINCIPLES
SINGLE SOURCE
OF TRUTH
the state of your whole application is stored in
an object tree within a single store
THE TRUTH IS OUT THERE
class SideBarComponent {



private visible: boolean;



toggle(){

this.visible = !this.visible

}

}
Stateful components
class TabsComponent {



private activeTab:Tab;



activateTab(tab) {

this.activeTab = tab;

}

}
Stateful components
class Accounts {



private accounts: Account[];



getAccounts() {

return this.accounts;

}

}
Data Models
const state = {

tabs: [],

accounts: [],

sidebar: {}

};
Application state
app state
STOREUI
stateless UI
THE STATE IS
READ ONLY
the only way to mutate the state is to emit an
action, an object describing what happened
class Store {



private state: Object;



getState(){

return this.state;

} 

}
Read-only State
STOREUI
STATEgetState()
STOREUI
STATEgetState()
ACTIONdispatch(action)
PURE FUNCTIONS
to specify how the state tree is transformed
by actions, you write pure functions.
PURE FUNCTION
return value is only determined by its input values,
without observable side effects.
PURE
FUNCTION
Current State
Action
Next State
Calculate the next state
PURE
FUNCTION
Current State
Action
Next State
Reducer
Calculate the next state
Uni directional data flow
UI STOREactions
state
ENTER THE STORE
THE STORE IS THE
HEART OF REDUX
TO CREATE A STORE
WE NEED A REDUCER
import { createStore } from 'redux';



const store = createStore(reducer);
import { createStore } from 'redux';



const store = createStore(reducer);
REDUCE METHOD
applies a function against an accumulator and
each value of the array (from left-to-right) to
reduce it to a single value.
function sum (previousVal, currentVal) {

return previousVal + currentVal;

}



[0, 1, 2, 3, 4].reduce(sum);
// => 10
Reduce in action
EVENT SOURCING
capture all changes to an application state as a
sequence of events.
function counter (state, action) {

switch (action) {

case 'up':

return state + 1;

case 'down':

return state - 1;

default:

return state;

}

}



['up', 'up', 'down'].reduce( counter, 0 );
Simple counter app
THE REDUCER RETURNS
THE NEXT STATE
BASED ON A SEQUENCE
OF ACTIONS
THE SAME SEQUENCE
OF ACTIONS
WILL PRODUCE THE
SAME STATE
PREDICTABLE
STATE CONTAINER
HANDS ON!
implementing a working store
in less then 30 lines of code.
function createStore(reducer) {

let state = null;

const listeners = [];



function getState() {

return state;

}



function dispatch(action) {

state = reducer(state, action);

listeners.forEach( listener => listener() )

}



function subscribe(listener) {

listeners.push(listener);

return function unsubscribe() {

let index = listeners.indexOf(listener);

listeners.splice(index, 1)

}

}



return { getState, dispatch, subscribe }

}
STORE API
dispatch(action)
subscribe(listener)
getState()
replaceReducer(reducer)
ASYNC DATA FLOW
MIDDLEWARE
extension point between dispatching an action,
and the moment it reaches the reducer.
Async flow with middlewares
UI STOREaction
state
Async flow with middlewares
UI STORE
state
MIDDLEWARE
action action
export const middleware = store => next => action => {

return next(action)

};
Middleware
- get the current state from the store
- pass an action to the next middleware
- access the provided action
ANGULAR & REDUX
ANGULAR IS A NEW
PLATFORM FOR BUILDING
COMPLEX MODERN SPA’S
https://github.com/nirkaufman/angular2-redux-workshop.git
http://tinyurl.com/h4bqmut
GET THE CODE
git checkout master
AN ANGULAR APP IS A
TREE OF COMPONENTS
WE MAP PROPERTIES
TO THE STATE
WE DISPATCH ACTIONS
IN REACTION TO EVENTS
COMPONENT
COMPONENT
STORE
[properties](events)
actions
state
git checkout 01_project-structure
ANGULAR 2.0
ENCOURAGING AN
OOP APPROACH
TO USE DEPENDENCY
INJECTIONS WITH REDUX
WE WRAP STUFF IN
PROVIDERS
import {createStore} from “redux";
import {RootReducer} from './reducers/root';


export class Store {



private store = createStore(rootReducer);



get state() {

return this.store.getState();

}



dispatch(action){

this.store.dispatch(action)

}

}
WE COMBINE MULTIPLY
REDUCERS TO ONE
ROOT REDUCER
import {combineReducers} from 'redux';



export const RootReducer = combineReducers({

app: (state = 0) => state

});
combineReducers in action
WE NEED TO REGISTER
OUR STORE PROVIDER
ON THE MODULE
@NgModule({

declarations: [AppComponent],

imports : [BrowserModule, HttpModule],

providers : [Store],

bootstrap : [AppComponent]

})
NOW WE CAN INJECT
IT TO OUR COMPONENT
AND GET THE STATE!
export class AppComponent {



constructor(store: Store) {

console.log(store.state);

}

}
git checkout 02_wiring
COMMON SCENARIOS
REQUIREMENTS
CRUD operations
Authentication
Notifications
Persistance
View modes
Logging
@Injectable()

export class ListActions {



private store:Store;



constructor(_store:Store) {

this.store = _store;

}



add(item) {

this.store.dispatch({

type : LIST.ADD_ITEM,

payload: item

})

}



remove(item) {

this.store.dispatch({

type : LIST.REMOVE_ITEM,

payload: item

})

}

}
The list actions class is
an helper for dispatching
actions to the store
git checkout 03_crud
@Injectable()

export class Auth {

private http:Http;

private URL:string;



constructor(_http:Http) {

this.http = _http;

this.URL = 'http://localhost:4000/api/login';

}



middleware = store => next => action => {



if (action.type !== USER.LOGIN) {

return next(action)


} else if (action.type === USER.LOGIN) {



const successHandler = result => next({

type : USER.LOGIN_SUCCESS,

payload: result.json()

});



const errorHandler = error => next({

type : USER.LOGIN_FAILED,

payload: error.json()

});



this.http.post(this.URL, action.payload)

.subscribe(successHandler, errorHandler);



return next({type: APP.LOADING})

}

}

}
By wrapping the
middleware in provider
we can use angular
services such as Http
git checkout 04_authentication
const initialState = {

loading: false

};



export function appReducer(state = initialState, action) {



switch (action.type) {

case APP.LOADING:

return Object.assign({}, state, {loading: true});



case APP.READY:

case USER.LOGIN_SUCCESS:

return Object.assign({}, state, {loading: false});



default:

return state;

}

}
‘application level’ reducer can handle
git checkout 05_spinner
GET READY FOR
TIME TRAVEL
DEBUGGING
class Model {



private items = [];





addItem(item) {}



updateIten(item) {...}



removeItem(item) {...}



}
separation of state from mutation methods
class ModelCrud {



static addItem(model, item) {…}



static updateIten(model, item) {…}



static removeItem(model, item) {…}



}
separation of state from mutation methods
const Model = {

items: []

};
git checkout 06_debugger
NEXT STEPS
Angular & Redux Workshop
https://leanpub.com/redux-book
THE COMPLETE
REDUX BOOK
Angular & Redux Workshop
RESOURCES
REDUX
http://redux.js.org/
https://egghead.io/series/getting-started-with-redux
CQRS & EVENT SOURCING
https://msdn.microsoft.com/en-us/library/dn568103.aspx
https://msdn.microsoft.com/en-us/library/dn589792.aspx
ANGULAR 2
angular-2-change-detection-explained.html
https://github.com/ngrx/store
https://github.com/angular-redux/ng2-redux
NIR KAUFMAN
nir@500tech.com
Head of Angular Development @ 500Tech
@nirkaufman
github.com/nirkaufman
meetup.com/Angular-AfterHours/
keep in touch!

More Related Content

What's hot (20)

PPTX
Redux in Angular2 for jsbe
Brecht Billiet
 
PDF
Boosting Angular runtime performance
Nir Kaufman
 
PDF
Angular redux
Nir Kaufman
 
PDF
Workshop 20: ReactJS Part II Flux Pattern & Redux
Visual Engineering
 
PDF
React + Redux. Best practices
Clickky
 
PDF
Intro to Redux | DreamLab Academy #3
DreamLab
 
PDF
Modern Web Developement
peychevi
 
PDF
Workshop 13: AngularJS Parte II
Visual Engineering
 
PDF
Workshop 19: ReactJS Introduction
Visual Engineering
 
PDF
Introduction to React & Redux
Boris Dinkevich
 
PDF
React & Redux
Federico Bond
 
PDF
Workshop 22: React-Redux Middleware
Visual Engineering
 
PDF
Creating a WYSIWYG Editor with React
peychevi
 
PDF
Using React, Redux and Saga with Lottoland APIs
Mihail Gaberov
 
PDF
Workshop 14: AngularJS Parte III
Visual Engineering
 
PDF
Workshop 23: ReactJS, React & Redux testing
Visual Engineering
 
PDF
Quick start with React | DreamLab Academy #2
DreamLab
 
PPTX
Redux training
dasersoft
 
PPTX
React with Redux
Stanimir Todorov
 
Redux in Angular2 for jsbe
Brecht Billiet
 
Boosting Angular runtime performance
Nir Kaufman
 
Angular redux
Nir Kaufman
 
Workshop 20: ReactJS Part II Flux Pattern & Redux
Visual Engineering
 
React + Redux. Best practices
Clickky
 
Intro to Redux | DreamLab Academy #3
DreamLab
 
Modern Web Developement
peychevi
 
Workshop 13: AngularJS Parte II
Visual Engineering
 
Workshop 19: ReactJS Introduction
Visual Engineering
 
Introduction to React & Redux
Boris Dinkevich
 
React & Redux
Federico Bond
 
Workshop 22: React-Redux Middleware
Visual Engineering
 
Creating a WYSIWYG Editor with React
peychevi
 
Using React, Redux and Saga with Lottoland APIs
Mihail Gaberov
 
Workshop 14: AngularJS Parte III
Visual Engineering
 
Workshop 23: ReactJS, React & Redux testing
Visual Engineering
 
Quick start with React | DreamLab Academy #2
DreamLab
 
Redux training
dasersoft
 
React with Redux
Stanimir Todorov
 

Viewers also liked (20)

PDF
Webstorm
Nir Kaufman
 
PDF
Angular Pipes Workshop
Nir Kaufman
 
PDF
Angular2 - getting-ready
Nir Kaufman
 
PDF
Angular2 workshop
Nir Kaufman
 
PDF
Up & running with ECMAScript6
Nir Kaufman
 
PDF
Angularjs - lazy loading techniques
Nir Kaufman
 
PDF
Building Universal Applications with Angular 2
Minko Gechev
 
PDF
Data Structures in javaScript 2015
Nir Kaufman
 
PDF
Solid angular
Nir Kaufman
 
PDF
Angularjs - Unit testing introduction
Nir Kaufman
 
PDF
Angular js routing options
Nir Kaufman
 
PDF
AngularJS performance & production tips
Nir Kaufman
 
PPTX
Angular 2 - Better or worse
Vladimir Georgiev
 
PDF
Angular 2 - Core Concepts
Fabio Biondi
 
PDF
How to Become a Thought Leader in Your Niche
Leslie Samuel
 
PDF
Webpack and angularjs
Nir Kaufman
 
PDF
AngularJS - Services
Nir Kaufman
 
PDF
Angular js - 10 reasons to choose angularjs
Nir Kaufman
 
PDF
Xamarin Dev Days - Introduction to Xamarin.Forms, Insights, Test Cloud
James Montemagno
 
PPTX
20140207 xamarin-red fabriq-microsoft-techdays-nativemobileappdevelopmentwith...
RedFabriQ
 
Webstorm
Nir Kaufman
 
Angular Pipes Workshop
Nir Kaufman
 
Angular2 - getting-ready
Nir Kaufman
 
Angular2 workshop
Nir Kaufman
 
Up & running with ECMAScript6
Nir Kaufman
 
Angularjs - lazy loading techniques
Nir Kaufman
 
Building Universal Applications with Angular 2
Minko Gechev
 
Data Structures in javaScript 2015
Nir Kaufman
 
Solid angular
Nir Kaufman
 
Angularjs - Unit testing introduction
Nir Kaufman
 
Angular js routing options
Nir Kaufman
 
AngularJS performance & production tips
Nir Kaufman
 
Angular 2 - Better or worse
Vladimir Georgiev
 
Angular 2 - Core Concepts
Fabio Biondi
 
How to Become a Thought Leader in Your Niche
Leslie Samuel
 
Webpack and angularjs
Nir Kaufman
 
AngularJS - Services
Nir Kaufman
 
Angular js - 10 reasons to choose angularjs
Nir Kaufman
 
Xamarin Dev Days - Introduction to Xamarin.Forms, Insights, Test Cloud
James Montemagno
 
20140207 xamarin-red fabriq-microsoft-techdays-nativemobileappdevelopmentwith...
RedFabriQ
 
Ad

Similar to Redux with angular 2 - workshop 2016 (20)

PDF
Angular2 and Redux - up & running - Nir Kaufman - Codemotion Amsterdam 2016
Codemotion
 
PDF
Ngrx slides
Christoffer Noring
 
PDF
Understanding redux
David Atchley
 
PDF
Introduction to Redux (for Angular and React devs)
Fabio Biondi
 
PDF
Redux in Angular 2+
Hùng Nguyễn Huy
 
PDF
Redux data flow with angular
Gil Fink
 
PDF
Redux State Management System A Comprehensive Review
ijtsrd
 
PPTX
an Introduction to Redux
Amin Ashtiani
 
PPTX
Redux Tech Talk
Chathuranga Jayanath
 
PPTX
downloads_introduction to redux.pptx
NavneetKumar111924
 
PPTX
Redux
Anurag Chitti
 
PDF
Dumb and smart components + redux (1)
Brecht Billiet
 
PDF
React Redux Tutorial | Redux Tutorial for Beginners | React Redux Training | ...
Edureka!
 
PDF
Redux data flow with angular
Gil Fink
 
PDF
Redux js
Nils Petersohn
 
PDF
Advanced Redux architecture - WHAT/WHEN/WHY/HOW
Mateusz Bosek
 
PDF
Basic Fundamental of Redux
InnovationM
 
PPTX
Redux workshop
Imran Sayed
 
PDF
Redux tutorial - intro to Redux by GetLittleTech
Oleg Kosuchin (GetLittleTech)
 
PDF
Egghead redux-cheat-sheet-3-2-1
Augustin Bralley
 
Angular2 and Redux - up & running - Nir Kaufman - Codemotion Amsterdam 2016
Codemotion
 
Ngrx slides
Christoffer Noring
 
Understanding redux
David Atchley
 
Introduction to Redux (for Angular and React devs)
Fabio Biondi
 
Redux in Angular 2+
Hùng Nguyễn Huy
 
Redux data flow with angular
Gil Fink
 
Redux State Management System A Comprehensive Review
ijtsrd
 
an Introduction to Redux
Amin Ashtiani
 
Redux Tech Talk
Chathuranga Jayanath
 
downloads_introduction to redux.pptx
NavneetKumar111924
 
Dumb and smart components + redux (1)
Brecht Billiet
 
React Redux Tutorial | Redux Tutorial for Beginners | React Redux Training | ...
Edureka!
 
Redux data flow with angular
Gil Fink
 
Redux js
Nils Petersohn
 
Advanced Redux architecture - WHAT/WHEN/WHY/HOW
Mateusz Bosek
 
Basic Fundamental of Redux
InnovationM
 
Redux workshop
Imran Sayed
 
Redux tutorial - intro to Redux by GetLittleTech
Oleg Kosuchin (GetLittleTech)
 
Egghead redux-cheat-sheet-3-2-1
Augustin Bralley
 
Ad

More from Nir Kaufman (9)

PDF
Angular Dependency Injection
Nir Kaufman
 
PDF
Angular Prestige: Less-known API and techniques
Nir Kaufman
 
PDF
Angular CLI custom builders
Nir Kaufman
 
PDF
Electronic music 101 for developers
Nir Kaufman
 
PDF
Nestjs MasterClass Slides
Nir Kaufman
 
PDF
Angular EE - Special Workshop by Nir Kaufman
Nir Kaufman
 
PDF
Decorators in js
Nir Kaufman
 
PDF
Styling recipes for Angular components
Nir Kaufman
 
PDF
Introduction To Angular's reactive forms
Nir Kaufman
 
Angular Dependency Injection
Nir Kaufman
 
Angular Prestige: Less-known API and techniques
Nir Kaufman
 
Angular CLI custom builders
Nir Kaufman
 
Electronic music 101 for developers
Nir Kaufman
 
Nestjs MasterClass Slides
Nir Kaufman
 
Angular EE - Special Workshop by Nir Kaufman
Nir Kaufman
 
Decorators in js
Nir Kaufman
 
Styling recipes for Angular components
Nir Kaufman
 
Introduction To Angular's reactive forms
Nir Kaufman
 

Recently uploaded (20)

PDF
Future-Proof or Fall Behind? 10 Tech Trends You Can’t Afford to Ignore in 2025
DIGITALCONFEX
 
PDF
Transcript: Book industry state of the nation 2025 - Tech Forum 2025
BookNet Canada
 
PDF
Transforming Utility Networks: Large-scale Data Migrations with FME
Safe Software
 
PDF
SIZING YOUR AIR CONDITIONER---A PRACTICAL GUIDE.pdf
Muhammad Rizwan Akram
 
PDF
Bitcoin for Millennials podcast with Bram, Power Laws of Bitcoin
Stephen Perrenod
 
PDF
UPDF - AI PDF Editor & Converter Key Features
DealFuel
 
DOCX
Cryptography Quiz: test your knowledge of this important security concept.
Rajni Bhardwaj Grover
 
PPTX
Mastering ODC + Okta Configuration - Chennai OSUG
HathiMaryA
 
PPTX
MuleSoft MCP Support (Model Context Protocol) and Use Case Demo
shyamraj55
 
PPTX
The Project Compass - GDG on Campus MSIT
dscmsitkol
 
PPTX
COMPARISON OF RASTER ANALYSIS TOOLS OF QGIS AND ARCGIS
Sharanya Sarkar
 
PDF
CIFDAQ Market Wrap for the week of 4th July 2025
CIFDAQ
 
PDF
Mastering Financial Management in Direct Selling
Epixel MLM Software
 
PDF
“NPU IP Hardware Shaped Through Software and Use-case Analysis,” a Presentati...
Edge AI and Vision Alliance
 
PDF
[Newgen] NewgenONE Marvin Brochure 1.pdf
darshakparmar
 
PPTX
Q2 FY26 Tableau User Group Leader Quarterly Call
lward7
 
PDF
“Computer Vision at Sea: Automated Fish Tracking for Sustainable Fishing,” a ...
Edge AI and Vision Alliance
 
PDF
POV_ Why Enterprises Need to Find Value in ZERO.pdf
darshakparmar
 
PPTX
Digital Circuits, important subject in CS
contactparinay1
 
PDF
NASA A Researcher’s Guide to International Space Station : Physical Sciences ...
Dr. PANKAJ DHUSSA
 
Future-Proof or Fall Behind? 10 Tech Trends You Can’t Afford to Ignore in 2025
DIGITALCONFEX
 
Transcript: Book industry state of the nation 2025 - Tech Forum 2025
BookNet Canada
 
Transforming Utility Networks: Large-scale Data Migrations with FME
Safe Software
 
SIZING YOUR AIR CONDITIONER---A PRACTICAL GUIDE.pdf
Muhammad Rizwan Akram
 
Bitcoin for Millennials podcast with Bram, Power Laws of Bitcoin
Stephen Perrenod
 
UPDF - AI PDF Editor & Converter Key Features
DealFuel
 
Cryptography Quiz: test your knowledge of this important security concept.
Rajni Bhardwaj Grover
 
Mastering ODC + Okta Configuration - Chennai OSUG
HathiMaryA
 
MuleSoft MCP Support (Model Context Protocol) and Use Case Demo
shyamraj55
 
The Project Compass - GDG on Campus MSIT
dscmsitkol
 
COMPARISON OF RASTER ANALYSIS TOOLS OF QGIS AND ARCGIS
Sharanya Sarkar
 
CIFDAQ Market Wrap for the week of 4th July 2025
CIFDAQ
 
Mastering Financial Management in Direct Selling
Epixel MLM Software
 
“NPU IP Hardware Shaped Through Software and Use-case Analysis,” a Presentati...
Edge AI and Vision Alliance
 
[Newgen] NewgenONE Marvin Brochure 1.pdf
darshakparmar
 
Q2 FY26 Tableau User Group Leader Quarterly Call
lward7
 
“Computer Vision at Sea: Automated Fish Tracking for Sustainable Fishing,” a ...
Edge AI and Vision Alliance
 
POV_ Why Enterprises Need to Find Value in ZERO.pdf
darshakparmar
 
Digital Circuits, important subject in CS
contactparinay1
 
NASA A Researcher’s Guide to International Space Station : Physical Sciences ...
Dr. PANKAJ DHUSSA
 

Redux with angular 2 - workshop 2016