Early praise for Build Reactive Websites with RxJS This book provides a programmatic path that builds a constructive understanding of RxJS and its many operators for both the novice and experienced JavaScript developer. ➤ Nathan Brenner Software Engineer, Mainz Brady Group This book provides practical approaches to understand the basics of RxJS observ- ables and the power of operators, as well as showing how to apply them to build actual applications. ➤ OJ Kwon RxJS core team member This book makes learning RxJS from scratch easy and fun. The real-world exer- cises interactively demonstrate each new concept, building on the previous ones. ➤ Chris Thielen Maintainer, UI-Router We've left this page blank to make the page numbers the same in the electronic and paper books. We tried just leaving it out, but then people wrote us to ask about the missing pages. Anyway, Eddy the Gerbil wanted to say “hello.” Build Reactive Websites with RxJS Master Observables and Wrangle Events Randall Koutnik The Pragmatic Bookshelf Raleigh, North Carolina Many of the designations used by manufacturers and sellers to distinguish their products are claimed as trademarks. Where those designations appear in this book, and The Pragmatic Programmers, LLC was aware of a trademark claim, the designations have been printed in initial capital letters or in all capitals. The Pragmatic Starter Kit, The Pragmatic Programmer, Pragmatic Programming, Pragmatic Bookshelf, PragProg and the linking g device are trade- marks of The Pragmatic Programmers, LLC. Every precaution was taken in the preparation of this book. However, the publisher assumes no responsibility for errors or omissions, or for damages that may result from the use of information (including program listings) contained herein. Our Pragmatic books, screencasts, and audio books can help you and your team create better software and have more fun. Visit us at https://pragprog.com. The team that produced this book includes: Publisher: Andy Hunt VP of Operations: Janet Furlow Managing Editor: Susan Conant Development Editor: Brian MacDonald Copy Editor: Paula Robertson Indexing: Potomac Indexing, LLC Layout: Gilson Graphics For sales, volume licensing, and support, please contact [email protected]. For international rights, please contact [email protected]. Copyright © 2018 The Pragmatic Programmers, LLC. All rights reserved. No part of this publication may be reproduced, stored in a retrieval system, or transmitted, in any form, or by any means, electronic, mechanical, photocopying, recording, or otherwise, without the prior consent of the publisher. ISBN-13: 978-1-68050-295-4 Book version: P1.0—December 2018 Contents Introduction . . . . . . . . . . . . . ix 1. Creating Observables . . . . . . . . . . . 1 Introducing Rx Concepts 1 Building a Stopwatch 4 Using a Subscription 13 Experimenting with Observables 14 What We Learned 17 2. Manipulating Streams . . . . . . . . . . 19 Translating Pig Latin with Flatten and Reduce 19 Flattening 21 Reducing 23 Debugging an Observable Stream 24 Typeahead 27 What We Learned 30 3. Managing Asynchronous Events . . . . . . . . 31 Making AJAX Requests 31 Handling Errors 32 Promises vs. Observables with AJAX 34 Loading with Progress Bar 36 When Good AJAX Goes Bad 39 Progressive and Ordered Loading 40 What We Learned 42 4. Advanced Async . . . . . . . . . . . . 43 The Spec 43 Preventing Race Conditions with switchMap 43 Debouncing Events 45 Adding Debounce to the Typeahead 47 Contents • vi Building a Stock Ticker 52 What We’ve Learned 57 5. Multiplexing Observables . . . . . . . . . 59 The Problem with Cold Observables 59 Multicasting with the Subject Class 62 Building a Chat Room 64 What We Learned 71 6. Using HTTP in Angular . . . . . . . . . . 73 Generating a New Project 75 Displaying Returned Data 81 Saving New Data 85 Routing to Components 86 Linking Between Components 87 Editing a Single Photo 89 Adding in Analytics 93 Intercepting HTTP Calls 95 What We Learned 97 7. Building Reactive Forms in Angular . . . . . . . 99 Building a Phone Number Input 99 Creating a Phone Input with Angular 103 Validating an Input 104 Building a Pizzeria Registration Form 106 Using Advanced Validation 109 Creating a Pizza Ordering Form 121 What We Learned 128 8. Advanced Angular . . . . . . . . . . . 131 Building Performant Applications 131 Managing State with ngrx 138 What We Learned 145 9. Reactive Game Development . . . . . . . . 147 Creating Your Own Operator 147 Animating Objects 149 Calling next with Schedulers 151 Architecting a Game 155 Tracking User Input 160 Creating Enemies 164 Detecting Collisions 166 Contents • vii What We Learned 167 Bonus Points 168 Index . . . . . . . . . . . . . . 169 Introduction Hello! If you’ve picked up this book, you’ve probably spent some time devel- oping websites. Whether you’re an old hand at slinging JavaScript or a new- comer to the frontend world, this book has something for you. The Goal of This Book The list of requirements for frontend work keeps increasing. You now need to build websites that load quickly on shaky connections, render perfectly on mobile devices, and respond with lightning speed to user input. All of these tasks require dealing with a high number of events from disparate sources, be it your CRM, late-breaking news, or just a chat room. The topic of this book, observables, is a new way of thinking about managing these events, even when they may occur sometime in the future. Observables are a neat concept, but what’s important is that you can keep things straight in your head, allowing you to build bigger, faster, and less-buggy applications for your users. It’s important to ask, with such a big claim as “simplifying frontend develop- ment,” what exactly is simplified? While RxJS (short for “Reactive eXtensions to JavaScript”) brings simplicity to many areas, this book focuses on two areas that can have you reaching for the aspirin time and time again: Asynchronous Calls and Control Flow JavaScript’s async-first design has been both a blessing and a curse. While the event loop allows us to fire off AJAX calls with ease, keeping track of them all can be quite the chore. A single AJAX request can be modeled as a promise, but more than one suddenly means there’s a cacophony of items to manually track (and even cancel) as the user progresses through our app. One of the most notorious examples, the typeahead, will be covered in Advanced Async. You’ll learn how to delegate both the calls and control flow to RxJS, allowing you to focus on the rest of your application. report erratum • discuss