Professional Documents
Culture Documents
Full Chapter Reactive Patterns With Rxjs For Angular A Practical Guide To Managing Your Angular Application S Data Reactively and Efficiently Using Rxjs 7 Lamis Chebbi PDF
Full Chapter Reactive Patterns With Rxjs For Angular A Practical Guide To Managing Your Angular Application S Data Reactively and Efficiently Using Rxjs 7 Lamis Chebbi PDF
Full Chapter Reactive Patterns With Rxjs For Angular A Practical Guide To Managing Your Angular Application S Data Reactively and Efficiently Using Rxjs 7 Lamis Chebbi PDF
https://textbookfull.com/product/reactive-programming-with-
angular-and-ngrx-learn-to-harness-the-power-of-reactive-
programming-with-rxjs-and-ngrx-extensions-1st-edition-oren-farhi-
auth/
https://textbookfull.com/product/reactive-programming-with-
rxjs-5-untangle-your-asynchronous-javascript-code-1st-edition-
sergi-mansilla/
https://textbookfull.com/product/essential-angular-for-asp-net-
core-mvc-3-a-practical-guide-to-successfully-using-both-in-your-
projects-2nd-edition-adam-freeman/
https://textbookfull.com/product/learn-with-angular-4-collected-
essays-angular-cli-unit-testing-debugging-typescript-and-angular-
build-processes-2nd-edition-jeffry-houser/
ng-book The Complete Guide to Angular Nate Murray
https://textbookfull.com/product/ng-book-the-complete-guide-to-
angular-nate-murray/
https://textbookfull.com/product/angular-up-and-running-learning-
angular-step-by-step-shyam-seshadri/
https://textbookfull.com/product/ng-book-the-complete-guide-to-
angular-5-nathan-murray/
https://textbookfull.com/product/ng-book-the-complete-guide-to-
angular-9-nathan-murray/
https://textbookfull.com/product/ng-book-the-complete-guide-to-
angular-11-felipe-coury/
Reactive Patterns
with RxJS
for Angular
Lamis Chebbi
BIRMINGHAM—MUMBAI
Reactive Patterns with RxJS for Angular
Copyright © 2022 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.
Associate Group Product Manager: Pavan Ramchandani
Publishing Product Manager: Ashitosh Gupta
Senior Editor: Mark Dsouza
Content Development Editor: Divya Vijayan
Technical Editor: Shubham Sharma
Copy Editor: Safis Editing
Project Coordinator: Ajesh Devavaram
Proofreader: Safis Editing
Indexer: Rekha Nair
Production Designer: Alishon Mendonca
Marketing Coordinator: Elizabeth Varghese
ISBN 978-1-80181-151-4
www.packt.com
To my father, who taught me diligence, perseverance, and 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.
Preface
Part 1 – Introduction
1
The Power of the Reactive Paradigm
Technical requirements 4 The HTTP client module 7
Exploring the pillars of reactive The router module 8
programming 4 Reactive forms 13
Data streams 4 The event emitter 14
Observer patterns 5 The async pipe 15
2
RxJS 7 – The Major Features
Technical requirements 20 The firstValueFrom() method 25
Exploring the bundle size The lastValueFrom() method 26
improvements 20 Empty errors 26
3
A Walkthrough of the Application
Technical requirements 32 View five – the modify recipe interface 36
Our app's user stories 32 View six – the recipe details interface 37
Summary59
5
Error Handling
Technical requirements 62 Exploring error handling
Understanding the anatomy of patterns and strategies 63
an Observable 62 Handling error operators 64
Table of Contents ix
6
Combining Streams
Technical requirements 80 Exploring the declarative
Defining the requirement 80 pattern for filtering data 85
Exploring the imperative The combineLatest operator 86
pattern for filtering data 81 The declarative pattern pillars 87
Emitting a value when an action occurs 90
A look at the filter component 81
A look at the recipes list component 82 Summary94
7
Transforming Streams
Technical requirements 96 Learning about other useful
Defining the requirement 96 higher-order mapping
operators107
Exploring the imperative
pattern for autosave 97 The mergeMap operator 107
The switchMap operator 108
Exploring the reactive pattern
The exhaustMap operator 109
for autosave 100
Higher-order observables 101 Summary110
Higher-order mapping operators 101
The concatMap operator 102
9
Caching Streams
Technical requirements 126 Exploring the RxJS 7
Defining the requirement 126 recommended pattern to
cache streams 133
Learning about using
the reactive pattern to Highlighting the use cases of
cache streams 127 caching streams 134
Summary135
10
Sharing Data between Components
Technical requirements 138 Step two – updating the last-selected
recipe140
Defining the requirement 138
Step three – consuming the
Exploring the reactive pattern last-selected recipe 142
to share data 139
Step one – creating a shared service 139 Highlighting other ways for
sharing data 144
Summary145
11
Bulk Operations
Technical requirements 147 The pattern in action 151
Defining the requirement 148 Learning about the reactive
Learning about the reactive pattern for tracking progress 156
pattern for bulk operations 149 Summary157
The forkJoin operator 150
Table of Contents xi
12
Processing Real-Time Updates
Technical requirements 160 Connection management 164
Defining the requirement 160 Putting the pattern into action 166
Index
Other Books You May Enjoy
Preface
Switching to a reactive mindset is one of the biggest challenges when you start learning
Reactive programming using RxJS. I believe that the reactive mindset is gradually
achieved by learning reactive patterns and comparing the reactive way with the imperative
one to distinguish the difference and the benefits.
That's why I wrote this book, which gathers a set of reactive patterns applied in an
Angular application. Learning reactive patterns helps with managing your application's
data efficiently, writing clean and maintainable code, reacting to user changes faster, and
consequently, enhancing the user experience.
So, all that you have to do is get started!
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 try block, you place your risky statements, and inside catch,
you handle the possible exceptions."
A block of code is set as follows:
behaviourSubject$.subscribe({
next: (message) => console.log(message),
error: (error) => console.log(error),
complete: () => console.log('Stream Completed'),
});
When we wish to draw your attention to a particular part of a code block, the relevant
lines or items are set in bold:
behaviourSubject$.subscribe({
next: (message) => console.log(message),
error: (error) => console.log(error),
complete: () => console.log('Stream Completed'),
});
xvi Preface
$ mkdir css
$ cd css
Bold: Indicates a new term, an important word, or words that you see onscreen. For
instance, words in menus or dialog boxes appear in bold. Here is an example: "Select
System info from the Administration panel."
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
customercare@packtpub.com 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 copyright@packt.com 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.
Preface xvii
In this section, you will understand the importance of using the reactive paradigm in
an Angular application, as well as the new features of RxJS 7. In the third chapter, we
will introduce the application that we are going to progressively build as we go through
the book.
This part comprises the following chapters:
Technical requirements
This chapter does not require an environment setup or installation steps. All the code
snippets here are just examples to illustrate the concepts. This book assumes that you have
a basic understanding of Angular and RxJS.
Data streams
Data streams are the spine of reactive programming. Everything that might change or
happen over time (you don't know when exactly) is represented as a stream, such as data,
events, notifications, and messages. Reactive programming is about reacting to changes as
soon as they are emitted!
An excellent example of data streams is UI events. Let's suppose that we have an HTML
button, and we want to execute an action whenever a user clicks on it. Here, we can think
of the click event as a stream:
//HTML code
<button id='save'>Save</button>
//TS code
const saveElement = document.getElementById('save');
saveElement.addEventListener('click', processClick);
Exploring the pillars of reactive programming 5
function processClick(event) {
console.log('Hi');
}
As implemented in the preceding code snippet, in order to react to this click event, we
register an EventListener event. Then, every time a click occurs, the processClick
method is called to execute a side effect. In our case, we are just logging Hi in the console.
As you might have gathered, to be able to react when something happens and execute
a side effect, you should listen to the streams to become notified. We can say listen or
observe to get closer to the reactive terminology. And this leads us to the observer design
pattern, which is at the heart of reactive programming.
Observer patterns
The observer pattern is based on two main roles: a publisher and a subscriber.
A publisher maintains a list of subscribers and notifies them or propagates a change every
time there is an update. On the other hand, a subscriber performs an update or executes a
side effect every time they receive a notification from the publisher:
This leads us to the building blocks of RxJS. They include the following:
• Observables: These are a representation of the data streams that notify the
observers of any change.
• Observers: These are the consumers of the data streams emitted by observables.
RxJS combines the observer pattern with the iterator pattern and functional programming
to process and handle asynchronous events.
This was a reminder of the fundamentals of reactive programming. Remember, it is
crucial to understand when to put a reactive implementation in place and when to
avoid it.
In general, whenever you have to handle asynchronous tasks in your Angular application,
always think of RxJS. The main advantages of RxJS over other asynchronous APIs are
listed as follows:
• RxJS makes dealing with event-based programs, asynchronous data calls, and
callbacks an easy task.
• Observables guarantee consistency. They emit multiple values over time so that you
can consume continuous data streams.
• Observables are lazy; they are not executed until you subscribe to them. This helps
with writing declarative code that is clean, efficient, and easy to understand and
maintain.
• Observables can be canceled, completed, and retrieved at any moment. This makes
a lot of sense in many real-world scenarios.
• RxJS provides many operators with a functional style to manipulate collections and
optimize side effects.
• Observables push errors to the subscribers and provide a clean way to handle errors.
• RxJS allows you to write clean and efficient code to handle asynchronous data in
your application.
Now that we have given some insight into the reactive programming pillars and detailed
the major advantages of RxJS, let's shed some light on the relationship between Angular
and RxJS.
Using RxJS in Angular and its advantages 7
Note
We recommend taking a quick look at https://angular.io/docs.
Here, you can find further details about the features mentioned earlier.
@Injectable()
export class RecipesService {
constructor(private http: HttpClient) { }
getRecipes(): Observable<Recipe[]> {
return this.http.get<Recipe[]>(`${BASE_PATH}/recipes/search/
8 The Power of the Reactive Paradigm
all`);
}
The following is the content of the environment.ts file where we define the
basePath property of our backend:
• Observables are cancellable, so you can cancel the HTTP request whenever you
want by calling the unsubscribe method.
• Also, you can retry HTTP requests when an error occurs or an exception is thrown.
• The server's response cannot be mutated by observables, although this can be the
case when chaining then() to promises.
Router events
The router exposes events as observables. The router events allow you to intercept the
navigation life cycle. The following list shows the sequence of router events:
• NavigationStart
• RouteConfigLoadStart
• RouteConfigLoadEnd
Using RxJS in Angular and its advantages 9
• RoutesRecognized
• GuardsCheckStart
• ChildActivationStart
• ActivationStart
• GuardsCheckEnd
• ResolveStart
• ResolveEnd
• ActivationEnd
• ChildActivationEnd
• NavigationEnd
• NavigationCancel
• NavigationError
• Scroll
Note
We recommend that you take a quick look at https://angular.io/
api/router/Event. Here, you can find further details about the events
and their order.
To intercept all the events that the router goes through, first, you should inject the
Router service, which provides navigation and URL manipulation capabilities. Then,
subscribe to the events observable available in the Router object, and filter the events
of the RouterEvent type using the rxjs filter operator.
This is an example of an Angular service that injects the Router object in the
constructor, subscribes to the router events, and just traces the event ID and path in the
console. However, note that you can also introduce pretty much any specific behavior:
You can filter any specific event by putting the target type. The following code example
only filters the NavigationStart event and traces the event ID and path inside the
console. However, you can also introduce pretty much any specific behavior:
@Injectable()
export class CustomRouteService {
constructor(public router: Router) {
this.router.events.pipe(
filter(event => event instanceof NavigationStart)
).subscribe((event: NavigationStart) => {
console.log(`The current event is : ${event.id} |
event.url`);
});
}
}
The majority of Angular applications have a routing mechanism. The router events change
frequently over time, and it makes sense to listen to changes to execute the side effects.
That's why observables are a flexible way in which to handle those streams.
Another random document with
no related content on Scribd:
Willets W, L’t 22d Mich Vol
Wands H P, Cap “ “
Welker W H, L’t 21st O Vol
Welshimer P, Cap 21st Ill Vol
Weatherby J, L’t 51st O Vol
Weesner T A, L’t 14 & 15 Ill V Bat
Wyman E F, C S
West D J, L’t 6th Conn Vol
Ware E W, L’t 9th Me Vol
White Dan, Col 31st Me Vol
Washburne W, Cap 35th Mass Vol
Wing G H, L’t 14th N Y Art
Wilder G O, Adj 15th Mass Vol
Willis A R, Cap 8th Me Vol
Wilcox C W, L’t 9th N H Vol
Westbrook U S, Cap 135th O Vol
Weeks E J, L’t 67th Pa Vol
Woodard J E, L’t 18th Conn Vol
Weakly T J, L’t 100th O Vol
Wright B F, Cap 146th N Y Vol
Wilson W M, Jr, Cap 122d O Vol
Watson J C, L’t 126th O Vol
Woodruff F M, L’t 76th N Y Vol
Wright D L, L’t 51st Ind Vol
Whiting J D, L’t 3d O Vol
Wright W R, Cap 80th Ill Vol
Wilson A, Cap “ “
Wolbach A R, L’t 3d O Vol
Woodrow J C, L’t 73d Ind Vol
Williamson J B, L’t 14th W Va Vol
Weaver J R, L’t 18th Pa Cav
Wilson H, L’t “ “
Worthen T A, L’t 118th Ill Vol
Wakefield H B, Can 55th Ind Vol
Whitman W S, L’t 66th Ind Vol
Wiltshire J W, L’t 45th O Vol
Weddle Geo, L’t 144th O Vol
Woodrow C W, L’t 19th Iowa Vol
Webb G W, Cap 2d Pa Art
White A B, L’t 4th Pa Cav
Warwick Jos F, L’t 101st Pa Vol
Willis H H, L’t 40th N Y Vol
Winship J, L’t 88th Ill Vol
Whitney J N, L’t 2d R I Cav
Wilson R, L’t 113th Ill Vol
Whitten B F, L’t 9th Me Vol
Whiteside J C, Cap 94th N Y Vol
Warren J W, L’t 1st Wis Cav
Wanzer G G, Major 24th N Y Cav
Wadsworth M C, L’t 16th Me Vol
Warchaw F, L’t 54th N Y Vol
Wilson W C, Cap 104th N Y Vol
White H G, Cap 94th N Y Vol
Widdess C C, Cap 150th Pa Vol
Whiston D, L’t 13th Mass Vol
Welsh W H H, L’t 87th Pa Vol
White C W, Cap 5th W Va Cav
Wilson J, Cap 57th O Vol
Williams W H, Cap 41st N Y Vol
Watson W L, L’t 21st Wis Vol
Winner C N, L’t 1st O Vol
Wasson J M, L’t 40th O Vol
Webb G W, Cap 2d Pa Art
Williams R, Cap 12th O Vol
Welch J C, L’t 85th N Y Vol
Wheeler J D, Cap 15th Conn Vol
Wenrick J E, 19th Pa Cav
Williams W, L’t 8th Mich Cav
Willis W, L’t 51st Ind Vol
Williams M F, L’t 15th Ky Vol
Wiley M, Cap 1st Tenn Vol
Whittaker E B, Cap 72d Pa Vol
Wallace J, L’t Col 47th O Vol
Ward T H, L’t 59th U S Cav
Wheaton J, L’t “ “
Wright R J, Cap 6th O Vol
Wilcox W H H, L’t 10th N Y Cav
Wallace R P, L’t 120th O Vol
Walpole H H, Cap 122d N Y Vol
Wright J W, L’t 10th Iowa Vol
Whittemore B W, L’t 5th N Y Vol
Wallace J J, L’t 7th Tenn Cav
Wentworth H A, L’t 14th N Y H Art
Wall M W, Cap 69th N Y Vol
Walker W H, L’t 4th O Vol
Wislon E S, L’t 1st Mass Cav
Warren D H, Ass Surg 8th Iowa Cav
Wilson R P, L’t 5th U S Cav
Willets W, L’t 22d Mich Vol
White H, Major
While G M, Cap 1st W Va Vol
Whitney J de W, O Vet Inf
Yaw E C, L’t 67th N Y Vol
York J H, L’t 63d Ind Vol
Youtz H C, Cap 126th O Vol
Young D G, Cap 81st Ill Vol
Young W J, L’t 111th Ill Vol
York E D, L’t 2d N C U Vol
Young J W, Major 76th NY Vol
Yates C H, L’t 96th Ill Vol
Young A, L’t 4th Pa Cav
Young T P, L’t 4th Ky Cav
Zarracher F K, Cap 18th Pa Cav
Zeigler Aaron, L’t 7th Pa V R C
Zeis H, Cap 80th Id Vol
Zimm A, L’t 15th Iowa Vol
Zobel C, L’t 15th N Y Art
Zeigler J D, L’t 114th Ill Vol
DEATHS.
Eckings T R, L’t 3d N J Vol
Henderson J H, L’t 14th Ill Vet Batn
Jackson R W, L’t 21st Wis Vol
Spafford A C, L’t 41st O Vol
Wenrick J E, Cap 19th Penn Cav
Young A, L’t 4th Penn Cav
JAS. A. GARFIELD.
Updated editions will replace the previous one—the old editions will
be renamed.
1.D. The copyright laws of the place where you are located also
govern what you can do with this work. Copyright laws in most
countries are in a constant state of change. If you are outside the
United States, check the laws of your country in addition to the terms
of this agreement before downloading, copying, displaying,
performing, distributing or creating derivative works based on this
work or any other Project Gutenberg™ work. The Foundation makes
no representations concerning the copyright status of any work in
any country other than the United States.
1.E.6. You may convert to and distribute this work in any binary,
compressed, marked up, nonproprietary or proprietary form,
including any word processing or hypertext form. However, if you
provide access to or distribute copies of a Project Gutenberg™ work
in a format other than “Plain Vanilla ASCII” or other format used in
the official version posted on the official Project Gutenberg™ website
(www.gutenberg.org), you must, at no additional cost, fee or expense
to the user, provide a copy, a means of exporting a copy, or a means
of obtaining a copy upon request, of the work in its original “Plain
Vanilla ASCII” or other form. Any alternate format must include the
full Project Gutenberg™ License as specified in paragraph 1.E.1.
• You pay a royalty fee of 20% of the gross profits you derive from
the use of Project Gutenberg™ works calculated using the
method you already use to calculate your applicable taxes. The
fee is owed to the owner of the Project Gutenberg™ trademark,
but he has agreed to donate royalties under this paragraph to
the Project Gutenberg Literary Archive Foundation. Royalty
payments must be paid within 60 days following each date on
which you prepare (or are legally required to prepare) your
periodic tax returns. Royalty payments should be clearly marked
as such and sent to the Project Gutenberg Literary Archive
Foundation at the address specified in Section 4, “Information
about donations to the Project Gutenberg Literary Archive
Foundation.”
• You provide a full refund of any money paid by a user who
notifies you in writing (or by e-mail) within 30 days of receipt that
s/he does not agree to the terms of the full Project Gutenberg™
License. You must require such a user to return or destroy all
copies of the works possessed in a physical medium and
discontinue all use of and all access to other copies of Project
Gutenberg™ works.
• You comply with all other terms of this agreement for free
distribution of Project Gutenberg™ works.
1.F.