Slide 1

Slide 1 text

github.com/CodeSequence/ngconf2019-ngrx-workshop CLONE AND FOLLOW THE SETUP INSTRUCTIONS

Slide 2

Slide 2 text

A REACTIVE STATE OF MIND WITH ANGULAR AND NGRX

Slide 3

Slide 3 text

Mike Ryan @MikeRyanDev

Slide 4

Slide 4 text

Mike Ryan @MikeRyanDev Software Engineer at Synapse

Slide 5

Slide 5 text

Mike Ryan @MikeRyanDev Software Engineer at Synapse Google Developer Expert

Slide 6

Slide 6 text

Mike Ryan @MikeRyanDev Software Engineer at Synapse Google Developer Expert NgRx Core Team

Slide 7

Slide 7 text

Brandon Roberts @brandontroberts

Slide 8

Slide 8 text

Brandon Roberts @brandontroberts Developer/Technical Writer

Slide 9

Slide 9 text

Brandon Roberts @brandontroberts Developer/Technical Writer Angular Team

Slide 10

Slide 10 text

Brandon Roberts @brandontroberts Developer/Technical Writer Angular Team NgRx Core Team

Slide 11

Slide 11 text

No content

Slide 12

Slide 12 text

Open source libraries for Angular

Slide 13

Slide 13 text

Open source libraries for Angular Built with reactivity in mind

Slide 14

Slide 14 text

Open source libraries for Angular Built with reactivity in mind State management and side effects

Slide 15

Slide 15 text

Open source libraries for Angular Built with reactivity in mind State management and side effects Community driven

Slide 16

Slide 16 text

DAY ONE SCHEDULE • Demystifying NgRx • Setting up the Store • Reducers • Actions • Entities • Selectors

Slide 17

Slide 17 text

FORMAT 1. Concept Overview 2. Demo 3. Challenge 4. Solution

Slide 18

Slide 18 text

Understand the architectural implications of NgRx and how to build Angular applications with it The Goal

Slide 19

Slide 19 text

DEMYSTIFYING NGRX

Slide 20

Slide 20 text

“How does NgRx work?”

Slide 21

Slide 21 text

“How does NgRx work?”

Slide 22

Slide 22 text

• NgRx prescribes an architecture for managing the state and side effects in you Angular application. It works by deriving a stream of updates for your application’s components called the “action stream”. • You apply a pure function called a “reducer” to the action stream as a means of deriving state in a deterministic way. • Long running processes called “effects” use RxJS operators to trigger side effects based on these updates and can optionally yield new changes back to the actions stream.

Slide 23

Slide 23 text

No content

Slide 24

Slide 24 text

No content

Slide 25

Slide 25 text

Let’s try this a different way

Slide 26

Slide 26 text

You already know how NgRx works

Slide 27

Slide 27 text

COMPONENTS

Slide 28

Slide 28 text

{live screenshot of movie search app}

Slide 29

Slide 29 text

{live screenshot of movie search app}

Slide 30

Slide 30 text

No content

Slide 31

Slide 31 text

Slide 32

Slide 32 text

Slide 33

Slide 33 text

Slide 34

Slide 34 text

Slide 35

Slide 35 text

Slide 36

Slide 36 text

@Input() movies: Movie[]

Slide 37

Slide 37 text

@Input() movie: Movie

Slide 38

Slide 38 text

@Output() favorite: EventEmitter

Slide 39

Slide 39 text

@Output() favoriteMovie: EventEmitter

Slide 40

Slide 40 text

@Output() search: EventEmitter

Slide 41

Slide 41 text

@Component({ template: ` ` }) class SearchMoviesPageComponent { movies: Movie[] = []; onSearch(searchTerm: string) { this.moviesService.findMovies(searchTerm) .subscribe(movies => { this.movies = movies; }); } }

Slide 42

Slide 42 text

@Component({ template: ` ` }) class SearchMoviesPageComponent { movies: Movie[] = []; onSearch(searchTerm: string) { this.moviesService.findMovies(searchTerm) .subscribe(movies => { this.movies = movies; }); } } STATE

Slide 43

Slide 43 text

@Component({ template: ` ` }) class SearchMoviesPageComponent { movies: Movie[] = []; onSearch(searchTerm: string) { this.moviesService.findMovies(searchTerm) .subscribe(movies => { this.movies = movies; }); } }

Slide 44

Slide 44 text

@Component({ template: ` ` }) class SearchMoviesPageComponent { movies: Movie[] = []; onSearch(searchTerm: string) { this.moviesService.findMovies(searchTerm) .subscribe(movies => { this.movies = movies; }); } } SIDE EFFECT

Slide 45

Slide 45 text

@Component({ template: ` ` }) class SearchMoviesPageComponent { movies: Movie[] = []; onSearch(searchTerm: string) { this.moviesService.findMovies(searchTerm) .subscribe(movies => { this.movies = movies; }); } }

Slide 46

Slide 46 text

@Component({ template: ` ` }) class SearchMoviesPageComponent { movies: Movie[] = []; onSearch(searchTerm: string) { this.moviesService.findMovies(searchTerm) .subscribe(movies => { this.movies = movies; }); } } STATE CHANGE

Slide 47

Slide 47 text

Slide 48

Slide 48 text

Connects data to components

Slide 49

Slide 49 text

Connects data to components Triggers side effects

Slide 50

Slide 50 text

Connects data to components Triggers side effects Handles state transitions

Slide 51

Slide 51 text

OUTSIDE WORLD

Slide 52

Slide 52 text

OUTSIDE WORLD

Slide 53

Slide 53 text

OUTSIDE WORLD

Slide 54

Slide 54 text

State flows down, changes flow up NGRX MENTAL MODEL

Slide 55

Slide 55 text

No content

Slide 56

Slide 56 text

No content

Slide 57

Slide 57 text

Connects data to components Triggers side effects Handles state transitions

Slide 58

Slide 58 text

Single Responsibility Principle

Slide 59

Slide 59 text

Slide 60

Slide 60 text

Connects data to components

Slide 61

Slide 61 text

@Input() and @Output()

Slide 62

Slide 62 text

@Component({ selector: 'movies-list-item', }) export class MoviesListItemComponent { @Input() movie: Movie; @Output() favorite = new EventEmitter(); }

Slide 63

Slide 63 text

@Component({ selector: 'movies-list-item', }) export class MoviesListItemComponent { @Input() movie: Movie; @Output() favorite = new EventEmitter(); } Does this component know who is binding to its input?

Slide 64

Slide 64 text

@Component({ selector: 'movies-list-item', }) export class MoviesListItemComponent { @Input() movie: Movie; @Output() favorite = new EventEmitter(); }

Slide 65

Slide 65 text

@Component({ selector: 'movies-list-item', }) export class MoviesListItemComponent { @Input() movie: Movie; @Output() favorite = new EventEmitter(); } Does this component know who is listening to its output?

Slide 66

Slide 66 text

Inputs & Outputs offer Indirection

Slide 67

Slide 67 text

There is indirection between consumer of state, how state changes, and side effects NGRX MENTAL MODEL

Slide 68

Slide 68 text

REDUCERS CONTAINERS EFFECTS

Slide 69

Slide 69 text

ACTIONS REDUCERS CONTAINERS EFFECTS

Slide 70

Slide 70 text

ACTIONS REDUCERS CONTAINERS EFFECTS

Slide 71

Slide 71 text

interface Action { type: string; }

Slide 72

Slide 72 text

this.store.dispatch({ type: 'MOVIES_LOADED_SUCCESS', movies: [{ id: 1, title: 'Enemy', director: 'Denis Villeneuve', }], });

Slide 73

Slide 73 text

Global @Output() for your whole app

Slide 74

Slide 74 text

EFFECTS REDUCERS CONTAINERS EFFECTS

Slide 75

Slide 75 text

EFFECTS REDUCERS CONTAINERS EFFECTS

Slide 76

Slide 76 text

No content

Slide 77

Slide 77 text

No content

Slide 78

Slide 78 text

@Effect() findMovies$ = this.actions$ .pipe( ofType('SEARCH_MOVIES'), switchMap(action => { return this.moviesService.findMovies(action.searchTerm) .pipe( map(movies => { return { type: 'MOVIES_LOADED_SUCCESS', movies, }; }) ) }), );

Slide 79

Slide 79 text

@Effect() findMovies$ = this.actions$ .pipe( ofType('SEARCH_MOVIES'), switchMap(action => { return this.moviesService.findMovies(action.searchTerm) .pipe( map(movies => { return { type: 'MOVIES_LOADED_SUCCESS', movies, }; }) ) }), );

Slide 80

Slide 80 text

@Effect() findMovies$ = this.actions$ .pipe( ofType('SEARCH_MOVIES'), switchMap(action => { return this.moviesService.findMovies(action.searchTerm) .pipe( map(movies => { return { type: 'MOVIES_LOADED_SUCCESS', movies, }; }) ) }), );

Slide 81

Slide 81 text

@Effect() findMovies$ = this.actions$ .pipe( ofType('SEARCH_MOVIES'), switchMap(action => { return this.moviesService.findMovies(action.searchTerm) .pipe( map(movies => { return { type: 'MOVIES_LOADED_SUCCESS', movies, }; }) ) }), );

Slide 82

Slide 82 text

@Effect() findMovies$ = this.actions$ .pipe( ofType('SEARCH_MOVIES'), switchMap(action => { return this.moviesService.findMovies(action.searchTerm) .pipe( map(movies => { return { type: 'MOVIES_LOADED_SUCCESS', movies, }; }) ) }), );

Slide 83

Slide 83 text

@Effect() findMovies$ = this.actions$ .pipe( ofType('SEARCH_MOVIES'), switchMap(action => { return this.moviesService.findMovies(action.searchTerm) .pipe( map(movies => { return { type: 'MOVIES_LOADED_SUCCESS', movies, }; }) ) }), );

Slide 84

Slide 84 text

REDUCERS REDUCERS CONTAINERS EFFECTS

Slide 85

Slide 85 text

REDUCERS REDUCERS CONTAINERS EFFECTS

Slide 86

Slide 86 text

REDUCER

Slide 87

Slide 87 text

REDUCER ACTIONS

Slide 88

Slide 88 text

REDUCER ACTIONS INITIAL STATE

Slide 89

Slide 89 text

REDUCER ACTIONS INITIAL STATE STATE

Slide 90

Slide 90 text

REDUCER ACTIONS INITIAL STATE STATE

Slide 91

Slide 91 text

function moviesReducer(state = [], action) { switch (action.type) { case 'MOVIES_LOADED_SUCCESS': { return action.movies; } default: { return state; } } }

Slide 92

Slide 92 text

function moviesReducer(state = [], action) { switch (action.type) { case 'MOVIES_LOADED_SUCCESS': { return action.movies; } default: { return state; } } }

Slide 93

Slide 93 text

function moviesReducer(state = [], action) { switch (action.type) { case 'MOVIES_LOADED_SUCCESS': { return action.movies; } default: { return state; } } }

Slide 94

Slide 94 text

function moviesReducer(state = [], action) { switch (action.type) { case 'MOVIES_LOADED_SUCCESS': { return action.movies; } default: { return state; } } }

Slide 95

Slide 95 text

function moviesReducer(state = [], action) { switch (action.type) { case 'MOVIES_LOADED_SUCCESS': { return action.movies; } default: { return state; } } }

Slide 96

Slide 96 text

function moviesReducer(state = [], action) { switch (action.type) { case 'MOVIES_LOADED_SUCCESS': { return action.movies; } default: { return state; } } }

Slide 97

Slide 97 text

function moviesReducer(state = [], action) { switch (action.type) { case 'MOVIES_LOADED_SUCCESS': { return action.movies; } default: { return state; } } }

Slide 98

Slide 98 text

function moviesReducer(state = [], action) { switch (action.type) { case 'MOVIES_LOADED_SUCCESS': { return action.movies; } default: { return state; } } }

Slide 99

Slide 99 text

function moviesReducer(state = [], action) { switch (action.type) { case 'MOVIES_LOADED_SUCCESS': { return action.movies; } default: { return state; } } }

Slide 100

Slide 100 text

SELECTORS REDUCERS CONTAINERS EFFECTS

Slide 101

Slide 101 text

SELECTORS REDUCERS CONTAINERS EFFECTS

Slide 102

Slide 102 text

STORE COMPONENTS ???

Slide 103

Slide 103 text

function selectMovies(state) { return state.moviesState.movies; }

Slide 104

Slide 104 text

Global @Input() for your whole app

Slide 105

Slide 105 text

CONTAINERS REDUCERS CONTAINERS EFFECTS

Slide 106

Slide 106 text

CONTAINERS REDUCERS CONTAINERS EFFECTS

Slide 107

Slide 107 text

@Component({ template: ` ` }) export class SearchMoviesPageComponent { movies$: Observable constructor(private store: Store) { this.movies$ = store.select(selectMovies); } onSearch(searchTerm: string) { this.store.dispatch({ type: 'SEARCH_MOVIES', searchTerm }); } }

Slide 108

Slide 108 text

@Component({ template: ` ` }) export class SearchMoviesPageComponent { movies$: Observable constructor(private store: Store) { this.movies$ = store.select(selectMovies); } onSearch(searchTerm: string) { this.store.dispatch({ type: 'SEARCH_MOVIES', searchTerm }); } }

Slide 109

Slide 109 text

@Component({ template: ` ` }) export class SearchMoviesPageComponent { movies$: Observable constructor(private store: Store) { this.movies$ = store.select(selectMovies); } onSearch(searchTerm: string) { this.store.dispatch({ type: 'SEARCH_MOVIES', searchTerm }); } }

Slide 110

Slide 110 text

@Component({ template: ` ` }) export class SearchMoviesPageComponent { movies$: Observable constructor(private store: Store) { this.movies$ = store.select(selectMovies); } onSearch(searchTerm: string) { this.store.dispatch({ type: 'SEARCH_MOVIES', searchTerm }); } }

Slide 111

Slide 111 text

@Component({ template: ` ` }) export class SearchMoviesPageComponent { movies$: Observable constructor(private store: Store) { this.movies$ = store.select(selectMovies); } onSearch(searchTerm: string) { this.store.dispatch({ type: 'SEARCH_MOVIES', searchTerm }); } }

Slide 112

Slide 112 text

@Input() movies: Movie[] store.select(selectMovies)

Slide 113

Slide 113 text

@Output() search: EventEmitter() this.store.dispatch({ type: 'SEARCH_MOVIES', searchTerm });

Slide 114

Slide 114 text

Select and Dispatch are special versions of Input and Output NGRX MENTAL MODEL

Slide 115

Slide 115 text

RESPONSIBILITIES

Slide 116

Slide 116 text

Containers connect data to components RESPONSIBILITIES

Slide 117

Slide 117 text

Containers connect data to components Effects triggers side effects RESPONSIBILITIES

Slide 118

Slide 118 text

Containers connect data to components Effects triggers side effects Reducers handle state transitions RESPONSIBILITIES

Slide 119

Slide 119 text

Delegate responsibilities to individual modules of code NGRX MENTAL MODEL

Slide 120

Slide 120 text

No content

Slide 121

Slide 121 text

State flows down, changes flow up

Slide 122

Slide 122 text

State flows down, changes flow up Indirection between state & consumer

Slide 123

Slide 123 text

State flows down, changes flow up Indirection between state & consumer Select & Dispatch => Input & Output

Slide 124

Slide 124 text

State flows down, changes flow up Indirection between state & consumer Select & Dispatch => Input & Output Adhere to single responsibility principle

Slide 125

Slide 125 text

github.com/CodeSequence/ngconf2019-ngrx-workshop

Slide 126

Slide 126 text

Demo

Slide 127

Slide 127 text

1. Clone the repo at 
 https://github.com/CodeSequence/ngconf2019-ngrx-workshop 2. Checkout the challenge branch 3. Familiarize yourself with the file structure 4. Where is movies state handled? 5. Where are the movies actions located? 6. How does the movies state flow into the movies component? 7. How are events in the movies component going to the movies reducer? Challenge github.com/CodeSequence/ngconf2019-ngrx-workshop Branch: challenge

Slide 128

Slide 128 text

SETTING UP THE STORE

Slide 129

Slide 129 text

State contained in a single state tree State in the store is immutable Slices of state are updated with reducers STORE

Slide 130

Slide 130 text

export interface MoviesState { activeMovieId: string | null; movies: Movie[]; }

Slide 131

Slide 131 text

export const initialState: MoviesState = { activeMovieId: null, movies: initialMovies, };

Slide 132

Slide 132 text

export function moviesReducer( state = initialState, action: Action ): MoviesState { switch (action.type) { default: return state; } }

Slide 133

Slide 133 text

import * as fromMovies from “./movies/movies.reducer”; import * as fromBooks from “./books/books.reducer”; export interface AppState { movies: fromMovies.MoviesState; books: fromBooks.BooksState; } export const reducers: ActionReducerMap = { movies: fromMovies.reducer, books: fromBooks.reducer };

Slide 134

Slide 134 text

@NgModule({ imports: [ // imports … StoreModule.forRoot(reducers), StoreDevtoolsModule.instrument({ maxAge: 5 }), ], }) export class AppModule {}

Slide 135

Slide 135 text

export class MoviesComponent implements OnInit { movies$: Observable; constructor(private store: Store) { this.movies$ = store.select( (state: AppState) => state.movies ); } }

Slide 136

Slide 136 text

Slide 137

Slide 137 text

STATE FLOWS DOWN

Slide 138

Slide 138 text

Demo

Slide 139

Slide 139 text

1. Open books.reducer.ts 2. Define an interface for BooksState that has activeBookId and books properties 3. Define an initialState object that implements the BooksState interface 4. Create a reducer that defaults to initialState with a default case in a switch statement that returns state Challenge, pt 1 PR: 00-setup github.com/CodeSequence/ngconf2019-ngrx-workshop

Slide 140

Slide 140 text

1. Open shared/state/index.ts and add books to the State interface and the books reducer to the reducers object 2. Open books-page.component.ts and inject the Store service into the constructor 3. Add an observable property to the component that gets all of the books from state using the select operator 4. Update books-page.component.html to use the async pipe to get the list of books Challenge, pt 2 PR: 00-setup github.com/CodeSequence/ngconf2019-ngrx-workshop

Slide 141

Slide 141 text

REDUCERS

Slide 142

Slide 142 text

Produce new states Receive the last state and next action Switch on the action type REDUCERS Use pure, immutable operations

Slide 143

Slide 143 text

export function reducer(state = initialState, action: Action): MoviesState { switch (action.type) { case "select": return { activeMovieId: action.movieId, movies: state.movies }; case "create": return { activeMovieId: state.selectedMovieId, movies: createMovie(state.movies, action.movie) }; default: return state; } }

Slide 144

Slide 144 text

const createMovie = (movies, movie) => [ ...movies, movie ]; const updateMovie = (movies, movie) => movies.map(w => { return w.id === movie.id ? Object.assign({}, movie, w) : w; }); const deleteMovie = (movies, movie) => movies.filter(w => movie.id !== w.id);

Slide 145

Slide 145 text

class MoviesComponent { createMovie(movie) { this.store.dispatch({ type: "create", movie }); } }

Slide 146

Slide 146 text

Demo

Slide 147

Slide 147 text

1. Update the books reducer to handle “select”, “clear select”, “create”, “update”, and “delete” actions 2. Use the helper functions already in books.reducer.ts 3. Update books-page.component.ts to dispatch “select”, “clear select”, “create”, “update”, and “delete” actions from the component 4. Remove the BooksService from the component Challenge PR: 01-reducers github.com/CodeSequence/ngconf2019-ngrx-workshop

Slide 148

Slide 148 text

ACTIONS

Slide 149

Slide 149 text

Unified interface to describe events Just data, no functionality Has at a minimum a type property ACTIONS Strongly typed using classes and enums

Slide 150

Slide 150 text

Unique events get unique actions Actions are grouped by their source Actions are never reused GOOD ACTION HYGIENE

Slide 151

Slide 151 text

class MoviesComponent { createMovie(movie) { this.store.dispatch({ type: "create", movie }); } }

Slide 152

Slide 152 text

export enum MoviesActionTypes { SelectMovie = "[Movies Page] Select Movie”, AddMovie = "[Movies Page] Add Movie", UpdateMovie = "[Movies Page] Update Movie", DeleteMovie = "[Movies Page] Delete Movie” }

Slide 153

Slide 153 text

export class SelectMovie implements Action { readonly type = MoviesActionTypes.SelectMovie; constructor(public movie) {} }

Slide 154

Slide 154 text

export class AddMovie implements Action { readonly type = MoviesActionTypes.AddMovie; constructor(public movie: MovieModel) {} } export class UpdateMovie implements Action { readonly type = MoviesActionTypes.UpdateMovie; constructor(public movie: MovieModel) {} } export class DeleteMovie implements Action { readonly type = MoviesActionTypes.DeleteMovie; constructor(public movie: MovieModel) {} }

Slide 155

Slide 155 text

export type MoviesActions = | SelectMovie | AddMovie | UpdateMovie | DeleteMovie;

Slide 156

Slide 156 text

export function moviesReducer( state = initialState, action: MoviesActions ): MoviesState { switch (action.type) { case MoviesActionTypes.MovieSelected: ... case MoviesActionTypes.AddMovie: ... case MoviesActionTypes.UpdateMovie: ... case MoviesActionTypes.DeleteMovie: ... default: return state; } }

Slide 157

Slide 157 text

createMovie(movie) { this.store.dispatch({ type: "create", movie }); }

Slide 158

Slide 158 text

createMovie(movie) { this.store.dispatch(new MoviesActions.AddMovie(movie)); }

Slide 159

Slide 159 text

Demo

Slide 160

Slide 160 text

1. Open books-page.actions.ts and create an enum to hold the various action types 2. Create strongly typed actions that adhere to good action hygiene for selecting a book, clearing the selection, creating a book, updating a book, and deleting a book. 3. Export the actions as a union type 4. Update books-page.components.ts and books.reducer.ts to use the new actions Challenge PR: 02-actions github.com/CodeSequence/ngconf2019-ngrx-workshop

Slide 161

Slide 161 text

ENTITIES

Slide 162

Slide 162 text

Working with collections should be fast Collections are very common Common set of basic state operations ENTITY Common set of basic state derivations

Slide 163

Slide 163 text

interface EntityState { ids: string[] | number[]; entities: { [id: string | number]: Model }; }

Slide 164

Slide 164 text

export interface MoviesState extends EntityState { activeMovieId: string | null; } export const adapter = createEntityAdapter(); export const initialState: Movie = adapter.getInitialState( { activeMovieId: null } );

Slide 165

Slide 165 text

export interface MoviesState extends EntityState { activeMovieId: string | null; } export const adapter = createEntityAdapter(); export const initialState: Movie = adapter.getInitialState( { activeMovieId: null } );

Slide 166

Slide 166 text

export interface MoviesState extends EntityState { activeMovieId: string | null; } export const adapter = createEntityAdapter(); export const initialState: Movie = adapter.getInitialState( { activeMovieId: null } );

Slide 167

Slide 167 text

export interface MoviesState extends EntityState { activeMovieId: string | null; } export const adapter = createEntityAdapter(); export const initialState: Movie = adapter.getInitialState( { activeMovieId: null } );

Slide 168

Slide 168 text

case MoviesActionTypes.AddMovie: return { activeMovieId: state.selectedMovieId, movies: createMovie(state.movies, action.movie) };

Slide 169

Slide 169 text

case MoviesActionTypes.AddMovie: return adapter.addOne(action.movie, state);

Slide 170

Slide 170 text

this.movies$ = store.select((state: any) => state.movies.ids.map(id => state.movies.entities[id]) );

Slide 171

Slide 171 text

Demo

Slide 172

Slide 172 text

1. Add an “Enter” action to books-page.actions.ts and dispatch it in the getBooks() method of books.component.ts 2. Update books.reducer.ts to use EntityState to define BooksState 3. Create an unsorted entity adapter for BooksState and use it to initialize initialState 4. Update the reducer to use the adapter methods 5. Add a case statement for the “Enter” action that adds all of the initialBooks to the state 6. Update the books$ selector in books-page.component.ts to use the ids and entities properties of the books state to get the list of books Challenge PR: 03-entity github.com/CodeSequence/ngconf2019-ngrx-workshop

Slide 173

Slide 173 text

SELECTORS

Slide 174

Slide 174 text

Allow us to query our store for data Recompute when their inputs change Fully leverage memoization for performance SELECTORS Selectors are fully composable

Slide 175

Slide 175 text

export const selectActiveMovieId = (state: MoviesState) => state.activeMovieId; // get and export the selectors export const { selectIds, selectEntities, selectAll } = adapter.getSelectors();

Slide 176

Slide 176 text

export const selectActiveMovie = createSelector( selectActiveMovieId, selectEntities, (activeMovieId, movieEntities) => movieEntities[activeMovieId], );

Slide 177

Slide 177 text

export const selectMoviesState = (state: AppState) => state.movies; export const selectAllMovies = createSelector( selectMoviesState, fromMovies.selectAll, ); export const selectActiveMovie = createSelector( selectMoviesState, fromMovies.selectActiveMovie, );

Slide 178

Slide 178 text

this.movies$ = store.select((state: any) => state.movies.ids.map(id => state.movies.entities[id]) );

Slide 179

Slide 179 text

this.movies$ = store.select(selectAllMovies);

Slide 180

Slide 180 text

Demo

Slide 181

Slide 181 text

1. Open books.reducer.ts and use the entity adapter to create selectors for selectAll and selectEntities 2. Write a selector in books.reducer.ts that gets activeBookId 3. Use createSelector to create a selectActiveBook selector using selectEntities and selectActiveBookId 4. Use createSelector to create a selectEarningsTotal selector to calculate the gross total earnings of all books using selectAll 5. Create global versions of selectAllBooks, selectActiveBook, and selectBookEarningsTotal in state/index.ts using createSelector 6. Update books-page.component.ts and its template to use the selectAllBooks, selectActiveBook, and selectEarningsTotal selectors Challenge PR: 04-selectors github.com/CodeSequence/ngconf2019-ngrx-workshop

Slide 182

Slide 182 text

No content

Slide 183

Slide 183 text

State flows down, changes flow up

Slide 184

Slide 184 text

State flows down, changes flow up Indirection between state & consumer

Slide 185

Slide 185 text

State flows down, changes flow up Indirection between state & consumer Select & Dispatch => Input & Output

Slide 186

Slide 186 text

State flows down, changes flow up Indirection between state & consumer Select & Dispatch => Input & Output Adhere to single responsibility principle

Slide 187

Slide 187 text

State contained in a single state tree State in the store is immutable Slices of state are updated with reducers STORE

Slide 188

Slide 188 text

Produce new states Receive the last state and next action Switch on the action type REDUCERS Use pure, immutable operations

Slide 189

Slide 189 text

Unified interface to describe events Just data, no functionality Has at a minimum a type property ACTIONS Strongly typed using classes and enums

Slide 190

Slide 190 text

Working with collections should be fast Collections are very common Common set of basic state operations ENTITY Common set of basic state derivations

Slide 191

Slide 191 text

Allow us to query our store for data Recompute when their inputs change Fully leverage memoization for performance SELECTORS Selectors are fully composable

Slide 192

Slide 192 text

DAY TWO SCHEDULE • Effects++ • Advanced Actions • Testing Reducers • Testing Effects • Wrap Up

Slide 193

Slide 193 text

github.com/CodeSequence/ngconf2019-ngrx-workshop CLONE AND FOLLOW THE SETUP INSTRUCTIONS

Slide 194

Slide 194 text

A REACTIVE STATE OF MIND WITH ANGULAR AND NGRX

Slide 195

Slide 195 text

Mike Ryan @MikeRyanDev

Slide 196

Slide 196 text

Mike Ryan @MikeRyanDev Software Engineer at Synapse

Slide 197

Slide 197 text

Mike Ryan @MikeRyanDev Software Engineer at Synapse Google Developer Expert

Slide 198

Slide 198 text

Mike Ryan @MikeRyanDev Software Engineer at Synapse Google Developer Expert NgRx Core Team

Slide 199

Slide 199 text

Brandon Roberts @brandontroberts

Slide 200

Slide 200 text

Brandon Roberts @brandontroberts Developer/Technical Writer

Slide 201

Slide 201 text

Brandon Roberts @brandontroberts Developer/Technical Writer Angular Team

Slide 202

Slide 202 text

Brandon Roberts @brandontroberts Developer/Technical Writer Angular Team NgRx Core Team

Slide 203

Slide 203 text

No content

Slide 204

Slide 204 text

State flows down, changes flow up

Slide 205

Slide 205 text

State flows down, changes flow up Indirection between state & consumer

Slide 206

Slide 206 text

State flows down, changes flow up Indirection between state & consumer Select & Dispatch => Input & Output

Slide 207

Slide 207 text

State flows down, changes flow up Indirection between state & consumer Select & Dispatch => Input & Output Adhere to single responsibility principle

Slide 208

Slide 208 text

REDUCERS CONTAINERS EFFECTS

Slide 209

Slide 209 text

REDUCERS CONTAINERS EFFECTS

Slide 210

Slide 210 text

1. Clone the repo at 
 https://github.com/CodeSequence/ngconf2019-ngrx-workshop 2. Checkout the 04-selectors branch 3. Familiarize yourself with the file structure 4. Where is books state handled? 5. Where are the books actions located? 6. How does the books state flow into the movies component? 7. How are events in the books page component going to the books reducer? Challenge github.com/CodeSequence/ngconf2019-ngrx-workshop Branch: 04-selectors

Slide 211

Slide 211 text

EFFECTS

Slide 212

Slide 212 text

REDUCERS CONTAINERS EFFECTS

Slide 213

Slide 213 text

REDUCERS CONTAINERS EFFECTS

Slide 214

Slide 214 text

Processes that run in the background Connect your app to the outside world Often used to talk to services EFFECTS Written entirely using RxJS streams

Slide 215

Slide 215 text

export enum MoviesApiActionTypes { MoviesLoaded = ‘[Movies API] Movies Loaded', MovieAdded = ‘[Movies API] Movie Added', MovieUpdated = ‘[Movies API] Movie Updated', MovieDeleted = ‘[Movies API] Movie Deleted' }

Slide 216

Slide 216 text

@Injectable() export class MoviesEffects { constructor( private actions$: Actions< BooksPageActions.BooksActions >, private moviesService: MoviesService ) {} }

Slide 217

Slide 217 text

export class MoviesEffects { @Effect() loadMovies$ = this.actions$.pipe( ofType(MoviesActionTypes.LoadMovies), mergeMap(() => this.moviesService.all().pipe( map( (res: MovieModel[]) => new MovieApiActions.MoviesLoaded(res) ), catchError(() => EMPTY) ) ) ); }

Slide 218

Slide 218 text

export class MoviesEffects { @Effect() loadMovies$ = this.actions$.pipe( ofType(MoviesActionTypes.LoadMovies), mergeMap(() => this.moviesService.all().pipe( map( (res: MovieModel[]) => new MovieApiActions.MoviesLoaded(res) ), catchError(() => EMPTY) ) ) ); }

Slide 219

Slide 219 text

export class MoviesEffects { @Effect() loadMovies$ = this.actions$.pipe( ofType(MoviesActionTypes.LoadMovies), mergeMap(() => this.moviesService.all().pipe( map( (res: MovieModel[]) => new MovieApiActions.MoviesLoaded(res) ), catchError(() => EMPTY) ) ) ); }

Slide 220

Slide 220 text

export class MoviesEffects { @Effect() loadMovies$ = this.actions$.pipe( ofType(MoviesActionTypes.LoadMovies), mergeMap(() => this.moviesService.all().pipe( map( (res: MovieModel[]) => new MovieApiActions.MoviesLoaded(res) ), catchError(() => EMPTY) ) ) ); }

Slide 221

Slide 221 text

EffectsModule.forFeature([MoviesEffects]);

Slide 222

Slide 222 text

const BASE_URL = "http://localhost:3000/movies"; @Injectable({ providedIn: "root" }) export class MoviesService { constructor(private http: HttpClient) {} load(id: string) { return this.http.get(`${BASE_URL}/${id}`); } }

Slide 223

Slide 223 text

export function moviesReducer( state = initialState, action: MoviesActions | MoviesApiActions): MoviesState { switch (action.type) { case MoviesApiActionTypes.MoviesLoaded: return adapter.addAll(action.movies, state); case MoviesApiActionTypes.MovieAdded: return adapter.addOne(action.movie, state); case MoviesActions.UpdateMovie: return adapter.upsertOne(action.movie, state); case MoviesActions.DeleteMovie: return adapter.removeOne(action.movie.id, state); default: return state; } }

Slide 224

Slide 224 text

Demo

Slide 225

Slide 225 text

1. Update books-api.actions.ts to export an action for BooksLoaded along with an action union type 2. Create a file at app/books/books-api.effects.ts and add an effect class to it with an effect called loadBooks$ that calls BooksService.all() and maps the result into a BooksLoaded action 3. Register the effect using EffectsModule.forFeature([]) in books.module.ts 4. Update the books reducer to handle the BooksLoaded action by replacing the Enter action handler Challenge PR: 05-effects github.com/CodeSequence/ngconf2019-ngrx-workshop

Slide 226

Slide 226 text

ADVANCED EFFECTS

Slide 227

Slide 227 text

export class MoviesEffects { @Effect() loadMovies$ = this.actions$.pipe( ofType(MoviesActionTypes.LoadMovies), mergeMap(() => this.moviesService.all().pipe( map( (res: MovieModel[]) => new MovieApiActions.MoviesLoaded(res) ), catchError(() => EMPTY) ) ) ); }

Slide 228

Slide 228 text

export class MoviesEffects { @Effect() loadMovies$ = this.actions$.pipe( ofType(MoviesActionTypes.LoadMovies), mergeMap(() => this.moviesService.all().pipe( map( (res: MovieModel[]) => new MovieApiActions.MoviesLoaded(res) ), catchError(() => EMPTY) ) ) ); }

Slide 229

Slide 229 text

WHAT MAP OPERATOR SHOULD I USE?

Slide 230

Slide 230 text

Subscribe immediately, never cancel or discard mergeMap Subscribe after the last one finishes concatMap Discard until the last one finishes exhaustMap Cancel the last one if it has not completed switchMap

Slide 231

Slide 231 text

Subscribe immediately, never cancel or discard mergeMap Discard until the last one finishes exhaustMap Cancel the last one if it has not completed switchMap RACE CONDITIONS!

Slide 232

Slide 232 text

CONCATMAP IS THE SAFEST OPERATOR …but there is a risk of back pressure

Slide 233

Slide 233 text

https://stackblitz.com/edit/angular-kbvxzz BACKPRESSURE DEMO

Slide 234

Slide 234 text

Deleting items mergeMap Updating or creating items concatMap Non-parameterized queries exhaustMap Parameterized queries switchMap

Slide 235

Slide 235 text

@Effect() enterMoviesPage$ = this.actions$.pipe( ofType(MoviesPageActions.Types.Enter), exhaustMap(() => this.movieService.all().pipe( map(movies => new MovieApiActions.LoadMoviesSuccess(movies)), catchError(() => of(new MovieApiActions.LoadMoviesFailure())) ) ) );

Slide 236

Slide 236 text

@Effect() updateMovie$ = this.actions$.pipe( ofType(MoviesPageActions.Types.UpdateMovie), concatMap(action => this.movieService.update(action.movie.id, action.changes).pipe( map(movie => new MovieApiActions.UpdateMovieSuccess(movie)), catchError(() => of(new MovieApiActions.UpdateMovieFailure(action.movie)) ) ) ) );

Slide 237

Slide 237 text

Demo

Slide 238

Slide 238 text

1. Add “Book Created”, “Book Updated”, and “Book Deleted” actions to books- api.actions.ts and update books.reducer.ts to handle these new actions 2. Open books-api.effects.ts and update the loadBooks$ effect to use the exhaustMap operator 3. Add an effect for creating a book using the BooksService.create() method and the concatMap operator 4. Add an effect for updating a book using the BooksService.update() method and the concatMap operator 5. Add an effect for deleting a book using the BooksService.delete() method and the mergeMap operator Challenge PR: 06-advanced-effects github.com/CodeSequence/ngconf2019-ngrx-workshop

Slide 239

Slide 239 text

ADVANCED ACTIONS

Slide 240

Slide 240 text

import { Action } from "@ngrx/store"; import { Book } from "src/app/shared/models/book.model"; export enum BooksApiActionTypes { BooksLoaded = "[Books API] Books Loaded Success", BookCreated = "[Books API] Book Created", BookUpdated = "[Books API] Book Updated", BookDeleted = "[Books API] Book Deleted" } export class BooksLoaded implements Action { readonly type = BooksApiActionTypes.BooksLoaded; constructor(public books: Book[]) {} } export class BookCreated implements Action { readonly type = BooksApiActionTypes.BookCreated; constructor(public book: Book) {} } export class BookUpdated implements Action { readonly type = BooksApiActionTypes.BookUpdated; constructor(public book: Book) {} } export class BookDeleted implements Action { readonly type = BooksApiActionTypes.BookDeleted; constructor(public book: Book) {} } export type BooksApiActions = | BooksLoaded | BookCreated | BookUpdated | BookDeleted;

Slide 241

Slide 241 text

import { Action } from "@ngrx/store"; import { Book } from "src/app/shared/models/book.model"; export enum BooksApiActionTypes { BooksLoaded = "[Books API] Books Loaded Success", BookCreated = "[Books API] Book Created", BookUpdated = "[Books API] Book Updated", BookDeleted = "[Books API] Book Deleted" } export class BooksLoaded implements Action { readonly type = BooksApiActionTypes.BooksLoaded;

Slide 242

Slide 242 text

import { Action } from "@ngrx/store"; import { Book } from "src/app/shared/models/book.model"; export enum BooksApiActionTypes { BooksLoaded = "[Books API] Books Loaded Success", BookCreated = "[Books API] Book Created", BookUpdated = "[Books API] Book Updated", BookDeleted = "[Books API] Book Deleted" } export class BooksLoaded implements Action { readonly type = BooksApiActionTypes.BooksLoaded;

Slide 243

Slide 243 text

import { Action } from "@ngrx/store"; import { Book } from "src/app/shared/models/book.model"; export enum BooksApiActionTypes { BooksLoaded = "[Books API] Books Loaded Success", BookCreated = "[Books API] Book Created", BookUpdated = "[Books API] Book Updated", BookDeleted = "[Books API] Book Deleted" } export class BooksLoaded implements Action { readonly type = BooksApiActionTypes.BooksLoaded;

Slide 244

Slide 244 text

export class BooksLoaded implements Action { readonly type = BooksApiActionTypes.BooksLoaded; constructor(public books: Book[]) {} } export class BookCreated implements Action { readonly type = BooksApiActionTypes.BookCreated; constructor(public book: Book) {} } export class BookUpdated implements Action { readonly type = BooksApiActionTypes.BookUpdated;

Slide 245

Slide 245 text

export class BooksLoaded implements Action { readonly type = BooksApiActionTypes.BooksLoaded; constructor(public books: Book[]) {} } export class BookCreated implements Action { readonly type = BooksApiActionTypes.BookCreated; constructor(public book: Book) {} } export class BookUpdated implements Action { readonly type = BooksApiActionTypes.BookUpdated;

Slide 246

Slide 246 text

export class BooksLoaded implements Action { readonly type = BooksApiActionTypes.BooksLoaded; constructor(public books: Book[]) {} } export class BookCreated implements Action { readonly type = BooksApiActionTypes.BookCreated; constructor(public book: Book) {} } export class BookUpdated implements Action { readonly type = BooksApiActionTypes.BookUpdated;

Slide 247

Slide 247 text

No content

Slide 248

Slide 248 text

No content

Slide 249

Slide 249 text

export const loadMoviesFailure = createAction( "[Movies API] Load Movies Failure" ); MovieApiActions.loadMoviesFailure();

Slide 250

Slide 250 text

export const updateMovieSuccess = createAction( "[Movies API] Update Movie Success", props<{ movie: Movie }>() ); MovieApiActions.updateMoviesSuccess({ movie });

Slide 251

Slide 251 text

export type Union = ReturnType< | typeof loadMoviesSuccess | typeof loadMoviesFailure // ... >;

Slide 252

Slide 252 text

@Effect() enterMoviesPage$ = this.actions$.pipe( ofType(MoviesPageActions.enter.type), exhaustMap(() => this.movieService.all().pipe( map(movies => MovieApiActions.loadMoviesSuccess({ movies })), catchError(() => of(MovieApiActions.loadMoviesFailure())) ) ) );

Slide 253

Slide 253 text

export function reducer( state: State = initialState, action: MovieApiActions.Union | MoviesPageActions.Union ): State { switch (action.type) { case MoviesPageActions.enter.type: { return { ...state, activeMovieId: null }; } default: { return state; } } }

Slide 254

Slide 254 text

Demo

Slide 255

Slide 255 text

1. Update books-page.actions.ts to use the createAction helper and the props factory function 2. Use the ReturnType utility type to replace the action union 3. Update books-api.actions.ts to use the createAction helper and the props factory function 4. Use the ReturnType utility type to replace the action union 5. Update books-page.component.ts, books-api.effects.ts, and books.reducer.ts to use the new action format Challenge PR: 07-action-creators github.com/CodeSequence/ngconf2019-ngrx-workshop

Slide 256

Slide 256 text

EFFECTS EXAMPLES

Slide 257

Slide 257 text

@Effect() tick$ = interval(/* Every minute */ 60 * 1000).pipe( map(() => Clock.tickAction(new Date())) );

Slide 258

Slide 258 text

@Effect() = fromWebSocket(“/ws").pipe(map(message => { switch (message.kind) { case “book_created”: { return WebSocketActions.bookCreated(message.book); } case “book_updated”: { return WebSocketActions.bookUpdated(message.book); } case “book_deleted”: { return WebSocketActions.bookDeleted(message.book); } } }))

Slide 259

Slide 259 text

@Effect() createBook$ = this.actions$.pipe( ofType(BooksPageActions.createBook.type), mergeMap(action => this.booksService.create(action.book).pipe( map(book => BooksApiActions.bookCreated({ book })), catchError(error => of(BooksApiActions.createFailure({ error, book: action.book, }))) ) ) );

Slide 260

Slide 260 text

@Effect() promptToRetry$ = this.actions$.pipe( ofType(BooksApiActions.createFailure), mergeMap(action => this.snackBar .open("Failed to save book.", "Try Again", { duration: /* 12 seconds */ 12 * 1000 }) .onAction() .pipe( map(() => BooksApiActions.retryCreate(action.book)) ) ) );

Slide 261

Slide 261 text

@Effect() promptToRetry$ = this.actions$.pipe( ofType(BooksApiActions.createFailure), mergeMap(action => this.snackBar .open("Failed to save book.", "Try Again", { duration: /* 12 seconds */ 12 * 1000 }) .onAction() .pipe( map(() => BooksApiActions.retryCreate(action.book)) ) ) ); Failed to save book. TRY AGAIN

Slide 262

Slide 262 text

@Effect() createBook$ = this.actions$.pipe( ofType( BooksPageActions.createBook, BooksApiActions.retryCreate, ), mergeMap(action => this.booksService.create(action.book).pipe( map(book => BooksApiActions.bookCreated({ book })), catchError(error => of(BooksApiActions.createFailure({ error, book: action.book, }))) ) ) );

Slide 263

Slide 263 text

@Effect({ dispatch: false }) openUploadModal$ = this.actions$.pipe( ofType(BooksPageActions.openUploadModal), tap(() => { this.dialog.open(BooksCoverUploadModalComponent); }) );

Slide 264

Slide 264 text

@Effect() uploadCover$ = this.actions$.pipe( ofType(BooksPageActions.uploadCover), concatMap(action => this.booksService.uploadCover(action.cover).pipe( map(result => BooksApiActions.uploadComplete(result)), takeUntil( this.actions$.pipe( ofType(BooksPageActions.cancelUpload) ) ) ) ) );

Slide 265

Slide 265 text

Testing Reducers TESTING REDUCERS

Slide 266

Slide 266 text

it("should return the initial state when initialized", () => { const state = reducer(undefined, { type: "@@init" } as any); expect(state).toBe(initialState); });

Slide 267

Slide 267 text

const movies: Movie[] = [ { id: "1", name: "Green Lantern", earnings: 0 } ]; const action = MovieApiActions.loadMoviesSuccess({ movies }); const state = reducer(initialState, action);

Slide 268

Slide 268 text

const movie: Movie = { id: "1", name: "mother!", earnings: 1000 }; const firstAction = MovieApiActions.createMovieSuccess({ movie }); const secondAction = MoviesPageActions.deleteMovie({ movie }); const state = [firstAction, secondAction].reduce( reducer, initialState );

Slide 269

Slide 269 text

const movies: Movie[] = [ { id: "1", name: "Green Lantern", earnings: 0 } ]; const action = MovieApiActions.loadMoviesSuccess({ movies }); const state = reducer(initialState, action); expect(selectAllMovies(state)).toEqual(movies);

Slide 270

Slide 270 text

expect(state).toEqual({ ids: ["1"], entities: { "1": { id: "1", name: "Green Lantern", earnings: 0 } } });

Slide 271

Slide 271 text

SNAPSHOT TESTING

Slide 272

Slide 272 text

expect(state).toMatchSnapshot();

Slide 273

Slide 273 text

exports[ `Movie Reducer should load all movies when the API loads them all successfully 1` ] = ` Object { "activeMovieId": null, "entities": Object { "1": Object { "earnings": 0, "id": "1", "name": "Green Lantern", }, }, "ids": Array [ "1", ], } `; in: shared/state/__snapshots__/movie.reducer.spec.ts.snap

Slide 274

Slide 274 text

Avoid writing out manual assertions Verify how state transitions impact state Can be used with components SNAPSHOT TESTING Creates snap files that get checked in

Slide 275

Slide 275 text

Demo

Slide 276

Slide 276 text

1. Write a test that verifies the books reducer returns the initial state when no state is provided using the toBe matcher 2. Write tests that verifies the books reducer correctly transitions state for loading all books, creating a book, and deleting a book using the toMatchSnapshot matcher 3. Write tests that verifies the behavior of the selectActiveBook and selectAll selectors Challenge PR: 08-reducer-testing github.com/CodeSequence/ngconf2019-ngrx-workshop

Slide 277

Slide 277 text

TESTING EFFECTS

Slide 278

Slide 278 text

OBSERVABLE TIMELINES

Slide 279

Slide 279 text

import { timer } from "rxjs"; import { mapTo } from "rxjs/operators"; timer(50).pipe(mapTo("a"));

Slide 280

Slide 280 text

timer(50).pipe(mapTo("a")); -----a|

Slide 281

Slide 281 text

timer(30).pipe(mergeMap(() => throwError(‘Error!'))) ---#

Slide 282

Slide 282 text

const source$ = timer(50).pipe(mapTo("a")); const expected$ = cold("-----a|"); expect(source$).toBeObservable(expected$);

Slide 283

Slide 283 text

const source$ = timer(30).pipe( mergeMap(() => throwError("Error!")) ); const expected$ = cold("---#", {}, "Error!"); expect(source$).toBeObservable(expected$);

Slide 284

Slide 284 text

10ms of time - Emission of any value a b c … Error # Completion |

Slide 285

Slide 285 text

COLD AND HOT OBSERVABLES

Slide 286

Slide 286 text

Cable TV COLD HOT

Slide 287

Slide 287 text

Hot Observable Actions Cold Observables HttpClient Hot Observable Store Cold Observable fromWebSocket

Slide 288

Slide 288 text

let actions$: Observable; beforeEach(() => { TestBed.configureTestingModule({ providers: [provideMockActions(() => actions$)] }); }); actions$ = hot("---a---", { a: BooksPageActions.enter });

Slide 289

Slide 289 text

const inputAction = MoviesPageActions.createMovie({ movie: { name: mockMovie.name, earnings: 25 } }); const outputAction = MovieApiActions.createMovieSuccess({ movie: mockMovie }); actions$ = hot("--a---", { a: inputAction }); const response$ = cold("--b|", { b: mockMovie }); const expected$ = cold("----c--", { c: outputAction }); mockMovieService.create.mockReturnValue(response$); expect(effects.createMovie$).toBeObservable(expected$);

Slide 290

Slide 290 text

Make assertions about time Describe Rx behavior with diagrams Verify observables behave as described JASMINE MARBLES Works with hot and cold observables

Slide 291

Slide 291 text

Demo

Slide 292

Slide 292 text

1. Open books-api.effects.spec.ts and declare variables for the actions$, instance of the effects, and a mock bookService 2. Use the TestBed to setup providers for the effects, actions, and the book service 3. Verify the behavior of the createBook$ effect using mock actions and test observables Challenge PR: 09-effects-testing github.com/CodeSequence/ngconf2019-ngrx-workshop

Slide 293

Slide 293 text

FOLDER LAYOUT

Slide 294

Slide 294 text

Locating our code is easy Identify code at a glance Flat file structure for as long as possible LIFT Try to stay DRY - don’t repeat yourself

Slide 295

Slide 295 text

src/ shared/ // Shared code modules/ ${feature}/ // Feature code

Slide 296

Slide 296 text

modules/ ${feature}/ actions/ ${action-category}.actions.ts index.ts components/ ${component-name}/ ${component-name}.component.ts ${component-name}.component.spec.ts services/ ${service-name}.service.ts ${service-name}.service.spec.ts effects/ ${effect-name}.effects.ts ${effect-name}.effects.spec.ts ${feature}.module.ts

Slide 297

Slide 297 text

modules/ book-collection/ actions/ books-page.actions.ts index.ts components/ books-page/ books-page.component.ts books-page.component.spec.ts services/ books.service.ts books.service.spec.ts effects/ books.effects.ts books.effects.spec.ts book-collection.module.ts

Slide 298

Slide 298 text

import * as BooksPageActions from "./books-page.actions"; import * as BooksApiActions from "./books-api.actions"; export { BooksPageActions, BooksApiActions }; ACTION BARRELS

Slide 299

Slide 299 text

import { BooksPageActions } from "app/modules/book-collection/actions";

Slide 300

Slide 300 text

src/ shared/ state/ ${state-name}/ ${state-key}/ ${state-key}.reducer.ts ${state-key}.spec.ts index.ts ${feature-name}.state.ts ${feature-name}.state.spec.ts ${feature-name}.state.module.ts index.ts effects/ ${effect-name}/ ${effect-name}.effects.ts ${effect-name}.effects.spec.ts ${effect-name}.actions.ts ${effect-name}.module.ts index.ts

Slide 301

Slide 301 text

src/ shared/ state/ core/ books/ books.reducer.ts books.spec.ts core.state.ts core.state.spec.ts core.state.module.ts index.ts effects/ clock/ clock.effects.ts clock.effects.spec.ts clock.actions.ts clock.module.ts

Slide 302

Slide 302 text

Put state in a shared place separate from features Effects, components, and actions belong to features Some effects can be shared FOLDER STRUCTURE Reducers reach into modules’ action barrels

Slide 303

Slide 303 text

“How does NgRx work?”

Slide 304

Slide 304 text

“How does NgRx work?”

Slide 305

Slide 305 text

No content

Slide 306

Slide 306 text

State flows down, changes flow up

Slide 307

Slide 307 text

State flows down, changes flow up Indirection between state & consumer

Slide 308

Slide 308 text

State flows down, changes flow up Indirection between state & consumer Select & Dispatch => Input & Output

Slide 309

Slide 309 text

State flows down, changes flow up Indirection between state & consumer Select & Dispatch => Input & Output Adhere to single responsibility principle

Slide 310

Slide 310 text

State contained in a single state tree State in the store is immutable Slices of state are updated with reducers STORE

Slide 311

Slide 311 text

Produce new states Receive the last state and next action Switch on the action type REDUCERS Use pure, immutable operations

Slide 312

Slide 312 text

Unified interface to describe events Just data, no functionality Has at a minimum a type property ACTIONS Strongly typed using createAction

Slide 313

Slide 313 text

Working with collections should be fast Collections are very common Common set of basic state operations ENTITY Common set of basic state derivations

Slide 314

Slide 314 text

Processes that run in the background Connect your app to the outside world Often used to talk to services EFFECTS Written entirely using RxJS streams

Slide 315

Slide 315 text

Avoid writing out manual assertions Verify how state transitions impact state Can be used with components SNAPSHOT TESTING Creates snap files that get checked in

Slide 316

Slide 316 text

Make assertions about time Describe Rx behavior with diagrams Verify observables behave as described JASMINE MARBLES Works with hot and cold observables

Slide 317

Slide 317 text

“How does NgRx work?”

Slide 318

Slide 318 text

“How does NgRx work?”

Slide 319

Slide 319 text

HELP US IMPROVE https://bit.ly/2ROXvn0

Slide 320

Slide 320 text

FOLLOW ON TALKS “Good Action Hygiene” by Mike Ryan https://youtu.be/JmnsEvoy-gY “Reactive Testing Strategies with NgRx” by Brandon Roberts & Mike Ryan https://youtu.be/MTZprd9tI6c “Authentication with NgRx” by Brandon Roberts https://youtu.be/46IRQgNtCGw “You Might Not Need NgRx” by Mike Ryan https://youtu.be/omnwu_etHTY “Just Another Marble Monday” by Sam Brennan & Keith Stewart https://youtu.be/dwDtMs4mN48

Slide 321

Slide 321 text

No content

Slide 322

Slide 322 text

@ngrx/schematics

Slide 323

Slide 323 text

@ngrx/schematics @ngrx/router-store

Slide 324

Slide 324 text

@ngrx/schematics @ngrx/router-store @ngrx/data

Slide 325

Slide 325 text

@ngrx/schematics @ngrx/router-store @ngrx/data ngrx.io

Slide 326

Slide 326 text

@MikeRyanDev @brandontroberts

Slide 327

Slide 327 text

THANK YOU