Reactive Patterns with RxJS and Angular Signals: Elevate your Angular 18 applications with RxJS Observables, subjects, operators, and Angular Signals
By Lamis Chebbi and Aristeidis Bampakos
()
About this ebook
RxJS is a powerful reactive extension for JavaScript, specializing in asynchronous and event-driven programming, but you don’t find many books on using RxJS in Angular applications. Written by an industry expert with over a decade of experience, this book helps you navigate reactive patterns, efficient data management, and the streamlined implementation of common features with minimal code.
This second edition aligns with the latest version of Angular, introducing new reactive patterns based on Angular Signals, which play a pivotal role in enabling fine-grained reactivity within Angular and enhancing change detection and user interface rendering. Throughout the book, you’ll construct a complete application that incorporates the latest Angular features, such as standalone components, new built-in control flow, deferrable views, and more. You’ll also focus on cultivating skills to handle data reactively, thus improving the application's overall quality, user experience, and developer productivity. The book covers best practices for testing asynchronous streams and optimizing app performance.
By the end of this RxJS and Angular book, you’ll not only be able to develop Angular applications by implementing reactive patterns, but also grasp all the best practices, ensuring a well-rounded understanding of RxJS within the Angular framework.
Related to Reactive Patterns with RxJS and Angular Signals
Related ebooks
Angular Design Patterns and Best Practices: Create scalable and adaptable applications that grow to meet evolving user needs Rating: 0 out of 5 stars0 ratingsAngular for Enterprise Applications: Build scalable Angular apps using the minimalist Router-first architecture Rating: 0 out of 5 stars0 ratingsEffective Angular: Develop applications of any size by effectively using Angular with Nx, RxJS, NgRx, and Cypress Rating: 0 out of 5 stars0 ratingsNode.js for Beginners: A comprehensive guide to building efficient, full-featured web applications with Node.js Rating: 0 out of 5 stars0 ratingsReact and React Native: Build cross-platform JavaScript and TypeScript apps for the web, desktop, and mobile Rating: 0 out of 5 stars0 ratingsReal-World Next.js: Build scalable, high-performance, and modern web applications using Next.js, the React framework for production Rating: 0 out of 5 stars0 ratingsReact Application Architecture for Production: Learn best practices and expert tips to deliver enterprise-ready React web apps Rating: 0 out of 5 stars0 ratingsModern API Design with gRPC Rating: 0 out of 5 stars0 ratingsLearn Angular: 4 Angular Projects Rating: 0 out of 5 stars0 ratingsLearn React with TypeScript: A beginner's guide to reactive web development with React 18 and TypeScript Rating: 0 out of 5 stars0 ratingsUltimate Microservices with Go Rating: 0 out of 5 stars0 ratingsObject Oriented Programming with Angular: Build and Deploy Your Web Application Using Angular with Ease ( English Edition) Rating: 0 out of 5 stars0 ratingsUltimate Node.js for Cross-Platform App Development Rating: 0 out of 5 stars0 ratingsJavaScript Design Patterns: Deliver fast and efficient production-grade JavaScript applications at scale Rating: 0 out of 5 stars0 ratingsReactive State for Angular with NgRx: Learn to build Reactive Angular Applications using NgRx (English Edition) Rating: 0 out of 5 stars0 ratingsReact Anti-Patterns: Build efficient and maintainable React applications with test-driven development and refactoring Rating: 0 out of 5 stars0 ratingsReact Projects..: Build advanced cross-platform projects with React and React Native to become a professional developer Rating: 0 out of 5 stars0 ratingsBuilding Your Own JavaScript Framework: Architect extensible and reusable framework systems Rating: 0 out of 5 stars0 ratingsPro Angular 16 Rating: 0 out of 5 stars0 ratingsApps and Services with .NET 8: Build practical projects with Blazor, .NET MAUI, gRPC, GraphQL, and other enterprise technologies Rating: 0 out of 5 stars0 ratingsUltimate Web Authentication Handbook Rating: 0 out of 5 stars0 ratingsAngular Cookbook: Over 80 actionable recipes every Angular developer should know Rating: 0 out of 5 stars0 ratingsUltimate Ember.js for Web App Development Rating: 0 out of 5 stars0 ratings
Internet & Web For You
How To Start A Profitable Authority Blog In Under One Hour Rating: 5 out of 5 stars5/5How to Be Invisible: Protect Your Home, Your Children, Your Assets, and Your Life Rating: 4 out of 5 stars4/5Coding For Dummies Rating: 5 out of 5 stars5/5Coding All-in-One For Dummies Rating: 4 out of 5 stars4/5Everybody Lies: Big Data, New Data, and What the Internet Can Tell Us About Who We Really Are Rating: 4 out of 5 stars4/5Social Engineering: The Science of Human Hacking Rating: 3 out of 5 stars3/5Python QuickStart Guide: The Simplified Beginner's Guide to Python Programming Using Hands-On Projects and Real-World Applications Rating: 0 out of 5 stars0 ratingsSurveillance and Surveillance Detection: A CIA Insider's Guide Rating: 3 out of 5 stars3/5Beginner's Guide To Starting An Etsy Print-On-Demand Shop Rating: 0 out of 5 stars0 ratingsNo Place to Hide: Edward Snowden, the NSA, and the U.S. Surveillance State Rating: 4 out of 5 stars4/5How to Disappear and Live Off the Grid: A CIA Insider's Guide Rating: 0 out of 5 stars0 ratingsWireless Hacking 101 Rating: 5 out of 5 stars5/5Cybersecurity All-in-One For Dummies Rating: 0 out of 5 stars0 ratingsThe Hacker Crackdown: Law and Disorder on the Electronic Frontier Rating: 4 out of 5 stars4/5Tor and the Dark Art of Anonymity Rating: 5 out of 5 stars5/5Six Figure Blogging Blueprint Rating: 5 out of 5 stars5/5Grokking Algorithms: An illustrated guide for programmers and other curious people Rating: 4 out of 5 stars4/5The $1,000,000 Web Designer Guide: A Practical Guide for Wealth and Freedom as an Online Freelancer Rating: 4 out of 5 stars4/5How To Make Money Blogging: How I Replaced My Day-Job With My Blog and How You Can Start A Blog Today Rating: 4 out of 5 stars4/5The Beginner's Affiliate Marketing Blueprint Rating: 4 out of 5 stars4/5Notion for Beginners: Notion for Work, Play, and Productivity Rating: 4 out of 5 stars4/5The Gothic Novel Collection Rating: 5 out of 5 stars5/5An Ultimate Guide to Kali Linux for Beginners Rating: 3 out of 5 stars3/5Ultimate guide for being anonymous: Avoiding prison time for fun and profit Rating: 5 out of 5 stars5/5Cybersecurity For Dummies Rating: 5 out of 5 stars5/5Podcasting For Dummies Rating: 4 out of 5 stars4/5COMPUTER SCIENCE FOR ROOKIES Rating: 0 out of 5 stars0 ratings
Reviews for Reactive Patterns with RxJS and Angular Signals
0 ratings0 reviews
Book preview
Reactive Patterns with RxJS and Angular Signals - Lamis Chebbi
Reactive Patterns with RxJS and Angular Signals
Copyright © 2024 Packt Publishing
All rights reserved. No part of this book may be reproduced, stored in a retrieval system, or transmitted in any form or by any means, without the prior written permission of the publisher, except in the case of brief quotations embedded in critical articles or reviews.
Every effort has been made in the preparation of this book to ensure the accuracy of the information presented. However, the information contained in this book is sold without warranty, either express or implied. Neither the author, nor Packt Publishing or its dealers and distributors, will be held liable for any damages caused or alleged to have been caused directly or indirectly by this book.
Packt Publishing has endeavored to provide trademark information about all of the companies and products mentioned in this book by the appropriate use of capitals. However, Packt Publishing cannot guarantee the accuracy of this information.
Group Product Manager: Kaustubh Manglurkar
Publishing Product Manager: Vaideeshwari Muralikrishnan
Senior Editor: Hayden Edwards
Technical Editor: Simran Ali
Copy Editor: Safis Editing
Project Coordinator: Shagun Saini
Proofreader: Safis Editing
Indexer: Rekha Nair
Production Designer: Jyoti Kadam
Marketing Coordinator: Anamika Singh and Nivedita Pandey
First edition published: April 2022
Second edition published: July 2024
Production reference: 1290524
Published by Packt Publishing Ltd
Grosvenor House
11 St Paul’s Square
Birmingham
B3 1RB
ISBN 978-1-83508-770-1
www.packtpub.com
To my father, who instilled in me diligence, perseverance, and a good work ethic. Thank you for always being there to support me and lift me up.
To my mother, who taught me selflessness and doing things with love. Thank you for your enduring encouragement during the writing of this book.
To my brother and my sisters, for their continuous support.
– Lamis Chebbi
Foreword
RxJS is a powerful JavaScript library that enables developers to build reactive and event-based web applications. The Angular framework uses this library to manage asynchronous operations, such as HTTP communication and user interaction with web forms and routing.
Angular Signals, a cutting-edge API, introduces fine-grained reactivity in Angular applications. This synchronous reactive pattern boosts performance and intelligently tracks the application state, optimizing component rendering and enhancing the overall user experience.
Reactive Patterns with RxJS and Angular Signals is a book that embraces both worlds, combining best practices from each tool to help you build performant and reactive Angular applications.
Lamis uses a simple yet insightful approach to RxJS and Signals, one which not only allows you to gain a deeper understanding of all the available reactive patterns in Angular, but also one that helps you build a complete application that encompasses all the latest features of the Angular framework.
Aristeidis Bampakos
Angular Google Developer Expert (GDE)
Contributors
About the author
Lamis Chebbi is a Google Developer Expert for Angular and is the author of the first edition of this book, titled Reactive Patterns with RxJS for Angular. She is an enthusiastic software engineer with a strong passion for the modern web, the founder of Angular Tunisia, a member of the WWCode community, a speaker, a content creator, and a trainer.
She has been interested in Angular and RxJS for the past few years and loves to share her knowledge about Angular by participating in workshops and organizing training sessions. Empowering women and students is one of her highest priorities.
Besides Angular and the web, Lamis loves music, traveling, chromotherapy, and volunteering.
Last but not least, she’s a forever student.
I want to thank all the people who believed in me, supported me, and inspired me throughout this journey.
About the reviewers
Aleksandr Guzenko is a respected software engineer known for his extensive expertise in both frontend and backend development. With over eight years of experience in the field, Aleksandr has made significant contributions to the software engineering community. His deep knowledge and practical skills are not only evident in his professional work but also in his active involvement as a judge in numerous hackathons.
Furthermore, Aleksandr is a sought-after speaker at conferences, where he shares his insights and experiences, particularly focusing on software architecture. He is also an author, of articles that delve into various aspects of software engineering.
Ishu Mishra is an IT specialist, working on frontend tech stacks for over 6 years. He began working at a start-up organization called Sparx IT Solutions, where he gained knowledge of Angular, and has worked for several companies since then.
Ishu previously worked for the Japanese multinational NEC Corporation, and presently, Ishu is employed in Bangalore by Morgan Stanley.
Matheus Rian is a frontend developer and speaker, who is passionate about technology and education. He started programming in high school and hasn’t stopped learning since, developing his skills in technologies such as Angular and React.
Furthermore, Matheus is a multiplier, seeking to disseminate knowledge and generate a positive impact within communities. As well as working in the frontend market, he gives lectures at events and contributes articles on Medium and dev.to.
Arthur Lannelucq is a passionate frontend developer specializing in Angular and RxJS. He is a strong advocate for reactive architectures, believing in their power to build responsive and scalable web applications.
He has gained solid experience working on various projects for large companies and start-ups. Eager to share his knowledge, he also runs a YouTube channel where he provides tutorials and practical advice on Angular and frontend development.
Table of Contents
Preface
Part 1: An Introduction to the Reactive World
1
Diving into the Reactive Paradigm
Technical requirements
Exploring the pillars of reactive programming
Data streams
Observer patterns
Learning about the marble diagram (our secret weapon)
Highlighting the use of RxJS in Angular
The HttpClient module
The Router module
Reactive forms
The Event emitter
Summary
2
Walking through Our Application
Technical requirements
Breaking down our app’s interfaces
View one – the landing page
View two – the New Recipe interface
View three – the My Recipes interface
View four – the My Favourites interface
View five – the Modify Recipe interface
View six – the Recipe Details interface
Reviewing our app’s architecture
Reviewing our app’s components
Summary
Part 2: A Trip into Reactive Patterns
3
Fetching Data as Streams
Technical requirements
Defining the data fetch requirement
Exploring the classic pattern for fetching data
Defining the structure of your data
Creating the fetching data service
Creating Angular standalone components
Injecting and subscribing to the service in your component
Displaying the data in the template
Managing unsubscriptions
Exploring the reactive pattern for fetching data
Retrieving data as streams
Defining the stream in your component
Using the async pipe in your template
Highlighting the advantages of the reactive pattern
Using the declarative approach
Using the change detection strategy of OnPush
Diving into the built-in control flow in Angular 17
Structural directives
Built-in control flows
Including built-in control flows in our recipe app
Benefits of built-in control flow
Summary
4
Handling Errors Reactively
Technical requirements
Understanding the anatomy of an Observable contract
Exploring error handling patterns and strategies
The replace strategy
The rethrow strategy
The retrying strategy
Choosing the right error handling strategy
Handling errors in our recipe app
Summary
5
Combining Streams
Technical requirements
Defining the filtering requirement
Exploring the imperative pattern for filtering data
Exploring the declarative pattern for filtering data
The combineLatest operator
Updating the filter value
Highlighting common pitfalls and best practices
Unnecessary subscriptions
Missing or incomplete values
Performance overhead
Confusing error handling
Summary
6
Transforming Streams
Technical requirements
Defining the autosave requirement
Exploring the imperative pattern for the autosave feature
Exploring the reactive pattern for the autosave feature
Higher-order Observables
Higher-order mapping operators
Summary
7
Sharing Data between Angular Components
Technical requirements
Defining the sharing data requirement
Exploring the reactive pattern to share data
Step 1 – Creating a shared service
Step 2 – Updating the last selected recipe
Step 3 – Consuming the last selected recipe
Wrapping up the data-sharing reactive pattern
Leveraging Deferrable Views in Angular 17
Summary
Part 3: The Power of Angular Signals
8
Mastering Reactivity with Angular Signals
Technical requirements
Understanding the motivation behind Signals
The traditional Zone.js approach
The new Signals approach
Unveiling the Signal API
Defining Signals
Creating Signals using the constructor function
Reading Signals
Modifying a writable Signal
Computed Signals
Signal effects
Unlocking the power of RxJS and Angular Signals
Understanding the behavior of toSignal()
Understanding the behavior of toObservable()
Integrating Signals into our recipe app
Fetching data as streams using Signals
Combining streams using Signals
Sharing data using Signals
Transforming streams using Signals
Exploring reactive data binding with Signals
Signal inputs
Model inputs
Signal queries
Summary
Part 4: Multicasting Adventures
9
Demystifying Multicasting
Technical requirements
Explaining multicasting versus unicasting
Unicasting and cold Observables
Multicasting and hot Observables
Transforming cold Observables into hot Observables
Exploring RxJS subjects
A plain subject
replaySubject
BehaviorSubject
Highlighting the advantages of multicasting
Summary
10
Boosting Performance with Reactive Caching
Technical requirements
Defining the caching requirement
Exploring the reactive pattern to cache streams
The shareReplay operator
Using shareReplay in RecipesApp
Customizing the shareReplay operator
Replacing the shareReplay operator with the share operator
Highlighting the use of caching for side effects
Summary
11
Performing Bulk Operations
Technical requirements
Defining the bulk operation requirements
Learning the reactive pattern for bulk operations
The forkJoin operator
The bulk operation reactive pattern
Benefits of the forkJoin operator
Learning the reactive pattern for tracking the bulk operation’s progress
Summary
12
Processing Real-Time Updates
Technical requirements
Defining the requirements of real time
Learning the reactive pattern for consuming real-time messages
Creating and using WebSocketSubject
WebSocketSubject in action
Learning the reactive pattern for handling reconnection
Summary
Part 5: Final Touches
13
Testing RxJS Observables
Technical requirements
Learning about the subscribe and assert pattern
Testing single-value output methods
Testing multiple-value output methods
Testing timed-value output methods
Learning about the marble testing pattern
Understanding the syntax
Introducing TestScheduler
Implementing marble tests
Testing timed-value output methods
Highlighting testing streams using HttpClientTestingModule
Summary
Index
Other Books You May Enjoy
Preface
Embarking on the journey from imperative to reactive programming is a significant shift and one that I have experienced firsthand. As I navigated this transition, I found myself drawn to the world of reactive patterns and the transformative power they held. It was a journey filled with discovery, comparison, and a strong determination to understand this new way of thinking.
Inspired by my own experiences, I’ve crafted this book to serve as a guide through the realms of reactive patterns within Angular applications. I believe that the reactive mindset is gradually achieved by comparing the reactive way to the imperative way, in order to distinguish the difference and benefits. Within these pages, you’ll discover how embracing reactive patterns can greatly enhance the way you manage data, write code, and react to user changes. From improving efficiency to creating cleaner, more manageable code bases, the benefits are vast and practical.
So, without further ado, let’s embark on this journey together and unlock the potential of reactive programming.
Who this book is for
If you’re a developer working with Angular and RxJS, this book is tailor-made for you. Designed for individuals at a beginner level in both Angular and RxJS, this book will guide you toward becoming an experienced developer while also benefitting those who wish to harness the potential of RxJS and leverage the reactive paradigm within their Angular applications.
What this book covers
In Chapter 1
, Diving into the Reactive Paradigm, you will learn the fundamentals of reactive programming.
In Chapter 2
, Walking through Our Application, you will learn the architecture and requirements of the recipe application that we will be building through the book.
In Chapter 3
, Fetching Data as Streams, you will learn the reactive pattern for fetching data so that we can reactively retrieve a list of recipes in our recipe app.
In Chapter 4
, Handling Errors Reactively, you will learn the different error strategies and the reactive patterns for handling errors.
In Chapter 5
, Combining Streams, you will learn the reactive pattern for combining streams and use it to implement a filter functionality in our recipe app, while also discovering the common pitfalls and sharing best practices for optimal implementation.
In Chapter 6
, Transforming Streams, you will learn the reactive pattern for transforming streams and use it to implement autosave and autocomplete features in our recipe app.
In Chapter 7
, Sharing Data between Angular Components, you will learn the reactive pattern to share data between components and use it to share the selected recipe in our recipe app.
In Chapter 8
, Mastering Reactivity with Angular Signals, you will deep-dive into Angular signals, learning different reactive patterns based on Angular Signals, and how to unleash the power of RxJS and Signals together. You will also discover the latest Angular Signals improvements.
In Chapter 9
, Demystifying Multicasting, you will learn the essentials of multicasting and the different multicasting concepts and operators offered by RxJS, such as Subjects, Behavior Subjects, and Replay Subjects.
In Chapter 10
, Boosting Performance with Reactive Caching, you will learn the reactive pattern to cache streams and implement a caching mechanism in our recipe app, based on the latest RxJS features.
In Chapter 11
, Performing Bulk Operations, you will learn the reactive pattern to perform bulk operations and implement a multiple asynchronous file upload in our recipe app.
In Chapter 12
, Processing Real-Time Updates, you will explore the reactive patterns to consume real-time updates and display newly created recipes instantly in our recipe app.
In Chapter 13
, Testing RxJS Observables, you will learn the different strategies to test reactive patterns and practice testing the API responses in our recipe app.
To get the most out of this book
This book assumes some familiarity with Angular, basic RxJS, TypeScript, and a foundational knowledge of functional programming. All code examples have been tested using Angular 17 and 18 on on the Windows OS. However, they should work with future version releases too.
Make sure you follow the prerequisites found here: https://angular.dev/tools/cli/setup-local
. The prerequisites include the environment setup and the technologies needed in order to install and use Angular.
We also use the Bootstrap library to manage the application’s responsiveness, the PrimeNG library for its rich components, and, of course, RxJS as the reactive library.
Plus, there is a ready-for-use backend server in the GitHub repository that we will only reference in our application.
If you are using the digital version of this book, we advise you to type the code yourself or access the code from the book’s GitHub repository (a link is available in the next section). Doing so will help you avoid any potential errors related to the copying and pasting of code.
Download the example code files
You can download the example code files for this book from GitHub at https://github.com/PacktPublishing/Reactive-Patterns-with-RxJS-and-Angular-Signals-Second-Edition
. If there’s an update to the code, it will be updated in the GitHub repository.
We also have other code bundles from our rich catalog of books and videos available at https://github.com/PacktPublishing/
. Check them out!
Conventions used
There are a number of text conventions used throughout this book.
Code in text: Indicates code words in text, database table names, folder names, filenames, file extensions, pathnames, dummy URLs, user input, and Twitter handles. Here is an example: In the following code snippet, we have an example of an Angular service that injects the HttpClient service and fetches data from the server using the HttpClient.get() method.
A block of code is set as follows:
import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { Observable} from 'rxjs';
Any command-line input or output is written as follows:
//console output
Full Name: John Doe
Bold: Indicates a new term, an important word, or words that you see on screen. For instance, words in menus or dialog boxes appear in bold. Here is an example: Users can create a new recipe by clicking on the New Recipe menu item located at the top right of the page.
Tips or important notes
Appear like this.
Get in touch
Feedback from our readers is always welcome.
General feedback: If you have questions about any aspect of this book, email us at [email protected]
and mention the book title in the subject of your message.
Errata: Although we have taken every care to ensure the accuracy of our content, mistakes do happen. If you have found a mistake in this book, we would be grateful if you would report this to us. Please visit www.packtpub.com/support/errata
and fill in the form.
Piracy: If you come across any illegal copies of our works in any form on the internet, we would be grateful if you would provide us with the location address or website name. Please contact us at [email protected]
with a link to the material.
If you are interested in becoming an author: If there is a topic that you have expertise in and you are interested in either writing or contributing to a book, please visit authors.packtpub.com
.
Share Your Thoughts
Once you’ve read Reactive Patterns with RxJS and Angular Signals, we’d love to hear your thoughts! Please click here to go straight to the Amazon review page
for this book and share your feedback.
Your review is important to us and the tech community and will help