Slide 1

Slide 1 text

Scalable Angular Applications Denis Kyashif

Slide 2

Slide 2 text

@deniskyashif deniskyashif deniskyashif.github.io

Slide 3

Slide 3 text

No content

Slide 4

Slide 4 text

Scalability

Slide 5

Slide 5 text

Scalability •Dynamic Requirements

Slide 6

Slide 6 text

Scalability •Dynamic Requirements •Increasing load

Slide 7

Slide 7 text

Scalability •Dynamic Requirements •Increasing load •Growing complexity

Slide 8

Slide 8 text

Scalability •Dynamic Requirements •Increasing load •Growing complexity •Developer turnover / Increasing team size

Slide 9

Slide 9 text

Software Design

Slide 10

Slide 10 text

Source: https://martinfowler.com/bliki/DesignStaminaHypothesis.html The Design Stamina Hypothesis

Slide 11

Slide 11 text

No content

Slide 12

Slide 12 text

No content

Slide 13

Slide 13 text

End Goal •Modular application •Predictable state management •Async data flow handling •Increased load capacity •Easy to test

Slide 14

Slide 14 text

No content

Slide 15

Slide 15 text

No content

Slide 16

Slide 16 text

class Queue { constructor(private data: T[] = []) { } enqueue(item: T) { return this.data.push(item); } dequeue = () : T => this.data.shift() } const n: number = 5; const queue = new Queue(); queue.enqueue(n); queue.enqueue('5'); // Error TypeScript

Slide 17

Slide 17 text

class Queue { constructor(private data: T[] = []) { } enqueue(item: T) { return this.data.push(item); } dequeue = () : T => this.data.shift() } const n: number = 5; const queue = new Queue(); queue.enqueue(n); queue.enqueue('5'); // Error TypeScript

Slide 18

Slide 18 text

class Queue { constructor(private data: T[] = []) { } enqueue(item: T) { return this.data.push(item); } dequeue = () : T => this.data.shift() } const n: number = 5; const queue = new Queue(); queue.enqueue(n); queue.enqueue('5'); // Error TypeScript

Slide 19

Slide 19 text

class Queue { constructor(private data: T[] = []) { } enqueue(item: T) { return this.data.push(item); } dequeue = () : T => this.data.shift(); } const n: number = 5; const queue = new Queue(); queue.enqueue(n); queue.enqueue('5'); // Error TypeScript

Slide 20

Slide 20 text

No content

Slide 21

Slide 21 text

A set of libraries for composing asynchronous and event-based programs using observable sequences.

Slide 22

Slide 22 text

const numbers = Observable.create(observer => { observer.next(1); observer.next(2); observer.next(3); setTimeout(() => { observer.next(4); // happens asynchronously }, 1000); }); numberEmitter.subscribe(console.log); // 1, 2, 3, ... 4 Observables

Slide 23

Slide 23 text

const numbers = Observable.create(observer => { observer.next(1); observer.next(2); observer.next(3); setTimeout(() => { observer.next(4); // happens asynchronously }, 1000); }); numberEmitter.subscribe(console.log); // 1, 2, 3, ... 4 Observables

Slide 24

Slide 24 text

const numbers = Observable.create(observer => { observer.next(1); observer.next(2); observer.next(3); setTimeout(() => { observer.next(4); // happens asynchronously }, 1000); }); numberEmitter.subscribe(console.log); // 1, 2, 3, ... 4 Observables

Slide 25

Slide 25 text

Operators const squaresOfEvenNumbers = interval(10) .pipe( filter(x => x % 2 === 0), map(x => x * x) ); squaresOfEvenNumbers.subscribe(console.log); // Output 0, 4, 16, 36...

Slide 26

Slide 26 text

Operators const squaresOfEvenNumbers = interval(10) .pipe( filter(x => x % 2 === 0), map(x => x * x) ); squaresOfEvenNumbers.subscribe(console.log); // Output 0, 4, 16, 36...

Slide 27

Slide 27 text

Operators const squaresOfEvenNumbers = interval(10) .pipe( filter(x => x % 2 === 0), map(x => x * x) ); squaresOfEvenNumbers.subscribe(console.log); // Output 0, 4, 16, 36...

Slide 28

Slide 28 text

Operators const squaresOfEvenNumbers = interval(10) .pipe( filter(x => x % 2 === 0), map(x => x * x) ); squaresOfEvenNumbers.subscribe(console.log); // Output 0, 4, 16, 36...

Slide 29

Slide 29 text

Observable Promise Emits multiple values over a period of time Emits a single value at a time Can be lazy Not lazy Can be cancelled Cannot be cancelled

Slide 30

Slide 30 text

Sample Application

Slide 31

Slide 31 text

Source: git.io/fpqkN

Slide 32

Slide 32 text

Sample Architecture

Slide 33

Slide 33 text

UI Components Facade State Management Data Access

Slide 34

Slide 34 text

UI Components Facade State Management Data Access

Slide 35

Slide 35 text

Container • Passes data to the presentational component • Handles events raised by presentational components • Interacts with the business layer Presentational • Takes data only as an @Input() • Delegates the event handling to the container via @Output() Components

Slide 36

Slide 36 text

Container Component Facade Presentational Component @Output() @Input() Components Actions Data

Slide 37

Slide 37 text

Source: git.io/fpqkN

Slide 38

Slide 38 text

Course Board Course List Course 1 Course 2 Course Details

Slide 39

Slide 39 text

course-details.component.ts export class CourseDetailsComponent { @Input() course: Course; @Output() delete = new EventEmitter(); constructor() { } onDeleteClick(course: Course) { this.delete.emit(course); } ... }

Slide 40

Slide 40 text

course-details.component.ts export class CourseDetailsComponent { @Input() course: Course; @Output() delete = new EventEmitter(); constructor() { } onDeleteClick(course: Course) { this.delete.emit(course); } ... }

Slide 41

Slide 41 text

course-board.component.ts export class CourseBoardComponent implements OnInit { courses$: Observable; selectedCourse$: Observable; constructor(private courses: CoursesStateService) { } ngOnInit() { this.courses.load(); this.courses$ = this.courses.getCourseList(); this.selectedCourse$ = this.courses.getSelectedCourse(); } delete(course: Course) { this.courses.delete(course); } ... }

Slide 42

Slide 42 text

course-board.component.html ...
...

Slide 43

Slide 43 text

course-board.component.html ...
...

Slide 44

Slide 44 text

UI Components Facade State Management Data Access

Slide 45

Slide 45 text

Facade A facade is an object that serves as a front-facing interface masking more complex underlying or structural code.

Slide 46

Slide 46 text

Client Classes Subsystem Classes

Slide 47

Slide 47 text

Client Classes Subsystem Classes Facade

Slide 48

Slide 48 text

courses.state.service.ts @Injectable({ providedIn: 'root' }) export class CoursesStateService { constructor(private store: Store) { } load() { this.store.dispatch(new CourseActions.Load()); } getCourseList(): Observable { return this.store.pipe(select(fromCourses.getCourseList)); } getSelectedCourse(): any { return this.store.pipe(select(fromCourses.getSelectedCourse)); } create(course: Course) { this.store.dispatch(new CourseActions.Create(course)); } ... }

Slide 49

Slide 49 text

courses.state.service.ts @Injectable({ providedIn: 'root' }) export class CoursesStateService { constructor(private store: Store) { } load() { this.store.dispatch(new CourseActions.Load()); } getCourseList(): Observable { return this.store.pipe(select(fromCourses.getCourseList)); } getSelectedCourse(): any { return this.store.pipe(select(fromCourses.getSelectedCourse)); } create(course: Course) { this.store.dispatch(new CourseActions.Create(course)); } ... }

Slide 50

Slide 50 text

courses.state.service.ts @Injectable({ providedIn: 'root' }) export class CoursesStateService { constructor(private store: Store) { } load() { this.store.dispatch(new CourseActions.Load()); } getCourseList(): Observable { return this.store.pipe(select(fromCourses.getCourseList)); } getSelectedCourse(): any { return this.store.pipe(select(fromCourses.getSelectedCourse)); } create(course: Course) { this.store.dispatch(new CourseActions.Create(course)); } ... }

Slide 51

Slide 51 text

Predictable State Management

Slide 52

Slide 52 text

UI Components Facade State Management Data Access

Slide 53

Slide 53 text

Or how I stopped worrying and learned to love

Slide 54

Slide 54 text

Source: https://css-tricks.com/learning-react-redux/

Slide 55

Slide 55 text

Redux •Single Source of Truth •State is Read-Only •Changes are made with Pure Functions

Slide 56

Slide 56 text

ngrx

Slide 57

Slide 57 text

State Management Store Reducers Effects Selectors Actions

Slide 58

Slide 58 text

Redux Terms State – an object that stores the state of the app Store – an immutable object that holds the state of the app View – a DOM representation of the state Action – an object describing an event. Used to send information to the store. Reducer – a pure function producing a new state out by given action and current state Selector – a function used to read from the store Effect – a middleware used to run side effects in isolation

Slide 59

Slide 59 text

Component Action Creator Store Reducer dispatch(action) applyReducers(action, state) next(state) newState

Slide 60

Slide 60 text

Component Action Creator Store Reducer dispatch(action) applyReducers(action, state) next(state) newState

Slide 61

Slide 61 text

Component Action Creator Store Reducer dispatch(action) applyReducers(action, state) next(state) newState

Slide 62

Slide 62 text

Component Action Creator Store Reducer dispatch(action) applyReducers(action, state) next(state) newState

Slide 63

Slide 63 text

Component Action Creator Store Reducer dispatch(action) applyReducers(action, state) next(state) newState

Slide 64

Slide 64 text

Component State Service (Facade) Store Reducer select(course) dispatch(new SelectAction(course))) applyReducers(action, state) next(state) New State

Slide 65

Slide 65 text

courses.state.ts export interface CoursesState { readonly courseList: Course[]; readonly selectedCourse?: Course; }

Slide 66

Slide 66 text

course.actions.ts export enum CourseActionTypes { Load = '[COURSE] Load', Create = '[COURSE] Create' ... } export class Load implements Action { readonly type = CourseActionTypes.Load; constructor(public payload: string = '') { } } export class Create implements Action { readonly type = CourseActionTypes.Create; constructor(public payload: Course) { } } ...

Slide 67

Slide 67 text

course.actions.ts export enum CourseActionTypes { Load = '[COURSE] Load', Create = '[COURSE] Create' ... } export class Load implements Action { readonly type = CourseActionTypes.Load; constructor(public payload: string = '') { } } export class Create implements Action { readonly type = CourseActionTypes.Create; constructor(public payload: Course) { } } ...

Slide 68

Slide 68 text

courses.reducer.ts ... export function coursesReducer( state: CoursesState = initialState, action: CourseActionsUnion): CoursesState { switch (action.type) { case CourseActionTypes.LoadSuccess: return { ...state, courseList: action.payload } case CourseActionTypes.CreateSuccess: return { ...state, courseList: [...state.courseList, action.payload] }; case CourseActionTypes.Select: return { ...state, selectedCourse: action.payload }; default: return state; } }

Slide 69

Slide 69 text

courses.reducer.ts ... export function coursesReducer( state: CoursesState = initialState, action: CourseActionsUnion): CoursesState { switch (action.type) { case CourseActionTypes.LoadSuccess: return { ...state, courseList: action.payload } case CourseActionTypes.CreateSuccess: return { ...state, courseList: [...state.courseList, action.payload] }; case CourseActionTypes.Select: return { ...state, selectedCourse: action.payload }; default: return state; } }

Slide 70

Slide 70 text

courses.reducer.ts ... export function coursesReducer( state: CoursesState = initialState, action: CourseActionsUnion): CoursesState { switch (action.type) { case CourseActionTypes.LoadSuccess: return { ...state, courseList: action.payload } case CourseActionTypes.CreateSuccess: return { ...state, courseList: [...state.courseList, action.payload] }; case CourseActionTypes.Select: return { ...state, selectedCourse: action.payload }; default: return state; } }

Slide 71

Slide 71 text

course-board.component.ts export class CourseBoardComponent implements OnInit { ... selectedCourse$: Observable; constructor(private courses: CoursesStateService) { } ngOnInit() { ... this.selectedCourse$ = this.courses.getSelectedCourse(); } ... }

Slide 72

Slide 72 text

course-board.component.ts export class CourseBoardComponent implements OnInit { ... selectedCourse$: Observable; constructor(private courses: CoursesStateService) { } ngOnInit() { ... this.selectedCourse$ = this.courses.getSelectedCourse(); } ... }

Slide 73

Slide 73 text

course-board.component.html ...
...

Slide 74

Slide 74 text

course-board.component.html ...
...

Slide 75

Slide 75 text

Managing Side Effects

Slide 76

Slide 76 text

Component State Service (Facade) Store Reducer login(credentials) dispatch(new LoginAction(credentials)) applyReducers(action, state) next(state) New State Effect Auth API login(credentials) onSuccess(res) dispatch(new LoginSuccessAction(user))

Slide 77

Slide 77 text

Component State Service (Facade) Store Reducer login(credentials) dispatch(new LoginAction(credentials)) applyReducers(action, state) next(state) New State Effect Auth API login(credentials) onSuccess(res) dispatch(new LoginSuccessAction(user))

Slide 78

Slide 78 text

Component State Service (Facade) Store Reducer login(credentials) dispatch(new LoginAction(credentials)) applyReducers(action, state) next(state) New State Effect Auth API login(credentials) onSuccess(res) dispatch(new LoginSuccessAction(user))

Slide 79

Slide 79 text

Component State Service (Facade) Store Reducer login(credentials) dispatch(new LoginAction(credentials)) applyReducers(action, state) next(state) New State Effect Auth API login(credentials) onSuccess(res) dispatch(new LoginSuccessAction(user))

Slide 80

Slide 80 text

Component State Service (Facade) Store Reducer login(credentials) dispatch(new LoginAction(credentials)) applyReducers(action, state) next(state) New State Effect Auth API login(credentials) onSuccess(res) dispatch(new LoginSuccessAction(user))

Slide 81

Slide 81 text

Component State Service (Facade) Store Reducer login(credentials) dispatch(new LoginAction(credentials)) applyReducers(action, state) next(state) New State Effect Auth API login(credentials) onSuccess(res) dispatch(new LoginSuccessAction(user))

Slide 82

Slide 82 text

Component State Service (Facade) Store Reducer login(credentials) dispatch(new LoginAction(credentials)) applyReducers(action, state) next(state) New State Effect Auth API login(credentials) onSuccess(res) dispatch(new LoginSuccessAction(user))

Slide 83

Slide 83 text

Component State Service (Facade) Store Reducer login(credentials) dispatch(new LoginAction(credentials)) applyReducers(action, state) next(state) New State Effect Auth API login(credentials) onSuccess(res) dispatch(new LoginSuccessAction(user))

Slide 84

Slide 84 text

Component State Service (Facade) Store Reducer login(credentials) dispatch(new LoginAction(credentials)) applyReducers(action, state) next(state) New State Effect Auth API login(credentials) onSuccess(res) dispatch(new LoginSuccessAction(user))

Slide 85

Slide 85 text

@Injectable() export class AuthEffects { @Effect() login$ = this.actions$.pipe( ofType(AuthActionTypes.Login), map(action => action.payload), exhaustMap((auth: Auth) => this.authApi.login(auth).pipe( map(user => new LoginSuccess({ username: auth.username }))) )); constructor(private actions$: Actions, private authApi: AuthApiService) { } } auth.effects.ts

Slide 86

Slide 86 text

@Injectable() export class AuthEffects { @Effect() login$ = this.actions$.pipe( ofType(AuthActionTypes.Login), map(action => action.payload), exhaustMap((auth: Auth) => this.authApi.login(auth).pipe( map(user => new LoginSuccess({ username: auth.username }))) )); constructor(private actions$: Actions, private authApi: AuthApiService) { } } auth.effects.ts

Slide 87

Slide 87 text

@Injectable() export class AuthEffects { @Effect() login$ = this.actions$.pipe( ofType(AuthActionTypes.Login), map(action => action.payload), exhaustMap((auth: Auth) => this.authApi.login(auth).pipe( map(user => new LoginSuccess({ username: auth.username }))) )); constructor(private actions$: Actions, private authApi: AuthApiService) { } } auth.effects.ts

Slide 88

Slide 88 text

@Injectable() export class AuthEffects { @Effect() login$ = this.actions$.pipe( ofType(AuthActionTypes.Login), map(action => action.payload), exhaustMap((auth: Auth) => this.authApi.login(auth).pipe( map(user => new LoginSuccess({ username: auth.username }))) )); constructor(private actions$: Actions, private authApi: AuthApiService) { } } auth.effects.ts

Slide 89

Slide 89 text

auth.reducer.ts export function authReducer(state: AuthState = initialState, action: AuthActionsUnion) { switch (action.type) { case AuthActionTypes.Login: return { ...state, loginPending: true, errorMessage: '' }; case AuthActionTypes.LoginSuccess: return { isLoggedIn: true, currentUser: action.payload, loginPending: false, errorMessage: '' }; ... }

Slide 90

Slide 90 text

UI Components Facade State Management Data Access

Slide 91

Slide 91 text

HTTP WebRTC WebSockets JSON XML Text Payloads Gateways Data Access

Slide 92

Slide 92 text

courses.api.service.ts @Injectable({ providedIn: 'root' }) export class CoursesApiService { private baseUrl = '/api/courses'; constructor(private http: HttpClient) { } get() : Observable { return this.http.get(this.baseUrl); } getById(id: string) : Observable { return this.http.get(`this.baseUrl/${id}`); } }

Slide 93

Slide 93 text

courses.api.service.ts @Injectable({ providedIn: 'root' }) export class CoursesApiService { private baseUrl = '/api/courses'; constructor(private http: HttpClient) { } get() : Observable { return this.http.get(this.baseUrl); } getById(id: string) : Observable { return this.http.get(`this.baseUrl/${id}`); } }

Slide 94

Slide 94 text

Redux DevTools

Slide 95

Slide 95 text

Change Detection

Slide 96

Slide 96 text

By default the change detection goes through every node of the component tree to see if it changed, and it does it on every browser event. Change Detection Rerefence: https://vsavkin.com/change-detection-in-angular-2-4f216b855d4c

Slide 97

Slide 97 text

App_ChangeDetector CourseBoard_ChangeDetector CourseList_ChangeDetector CourseDetails_ChangeDetector

Slide 98

Slide 98 text

App_ChangeDetector CourseBoard_ChangeDetector CourseList_ChangeDetector CourseDetails_ChangeDetector

Slide 99

Slide 99 text

App_ChangeDetector CourseBoard_ChangeDetector CourseList_ChangeDetector CourseDetails_ChangeDetector

Slide 100

Slide 100 text

App_ChangeDetector CourseBoard_ChangeDetector CourseList_ChangeDetector CourseDetails_ChangeDetector

Slide 101

Slide 101 text

App_ChangeDetector CourseBoard_ChangeDetector CourseList_ChangeDetector CourseDetails_ChangeDetector

Slide 102

Slide 102 text

Immutable Objects If a component depends only on its input properties, and they are immutable, then this component can change if and only if one of its input properties changes. Rerefence: https://vsavkin.com/change-detection-in-angular-2-4f216b855d4c

Slide 103

Slide 103 text

course-details.component.ts @Component({ ... changeDetection: ChangeDetectionStrategy.OnPush }) export class CourseDetailsComponent { @Input() course: Course; @Output() delete = new EventEmitter(); constructor() { } onDeleteClick(course: Course) { this.delete.emit(course); } ... }

Slide 104

Slide 104 text

course-details.component.ts @Component({ ... changeDetection: ChangeDetectionStrategy.OnPush }) export class CourseDetailsComponent { @Input() course: Course; @Output() delete = new EventEmitter(); constructor() { } onDeleteClick(course: Course) { this.delete.emit(course); } ... }

Slide 105

Slide 105 text

App_ChangeDetector CourseBoard_ChangeDetector CourseList_ChangeDetector CourseDetails_ChangeDetector

Slide 106

Slide 106 text

App_ChangeDetector CourseBoard_ChangeDetector CourseList_ChangeDetector CourseDetails_ChangeDetector

Slide 107

Slide 107 text

Modules

Slide 108

Slide 108 text

Core Module App Module Feature A Module Feature B Module Shared Module

Slide 109

Slide 109 text

Lazy Loading

Slide 110

Slide 110 text

Core Module App Module Feature A Module Feature B Module Feature C Module Shared Module Shared Module App Injector Lazy Module Injector

Slide 111

Slide 111 text

Properties • Modular project (Feature modules and lazy loading)

Slide 112

Slide 112 text

Properties • Modular project (Feature modules and lazy loading) • Predictable state management (Redux)

Slide 113

Slide 113 text

Properties • Modular project (Feature modules and lazy loading) • Predictable state management (Redux) • Increased load capacity (immutability, detect changes on push)

Slide 114

Slide 114 text

Properties • Modular project (Feature modules and lazy loading) • Predictable state management (Redux) • Increased load capacity (immutability, detect changes on push) • Async data flow handling (RxJS)

Slide 115

Slide 115 text

Properties • Modular project (Feature modules and lazy loading) • Predictable state management (Redux) • Increased load capacity (immutability, detect changes on push) • Async data flow handling (RxJS) • Easy to test (DI and easy to mock service layer)

Slide 116

Slide 116 text

Sample Tech Stack •TypeScript •RxJS •ngrx/store •ngrx/effects •ImmutableJS

Slide 117

Slide 117 text

This does not replace common sense!

Slide 118

Slide 118 text

No content

Slide 119

Slide 119 text

Reims Cathedral, France

Slide 120

Slide 120 text

It is better to have a system omit certain anomalous features and improvements, but to reflect one set of design ideas, than to have one that contains many good but independent and uncoordinated ideas. Frederick P. Brooks, “The Mythical Man-Month” Conceptual Integrity

Slide 121

Slide 121 text

References • Redux Docs https://redux.js.org/introduction • @ngrx docs https://ngrx.github.io/ • Managing State in Angular Applications https://blog.nrwl.io/managing-state-in-angular-applications-22b75ef5625f • Change Detection in Angular https://vsavkin.com/change-detection-in-angular-2-4f216b855d4c • On Push Change Detection and Immutability https://blog.mgechev.com/2017/11/11/faster-angular-applications-onpush-change-detection-immutable- part-1/ • Making Architecture Matter by Martin Fowler https://www.youtube.com/watch?v=DngAZyWMGR0

Slide 122

Slide 122 text

@deniskyashif deniskyashif deniskyashif.github.io Thank You!