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 download
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 download
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
[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.
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.
Random documents with unrelated
content Scribd suggests to you:
Chapter Seven.
It was evening when we got back to the encampment. On
casting our eyes towards the ship, her appearance, as she
lay overlapped with masses of ice on her beam ends, could
not fail to produce a melancholy feeling.
The next day all was quiet. The captain was of opinion that
we should move no further north, and that, should our floe
become detached, we might expect to drift to the
southward.
Satisfied that our visitors were Polar bears which must have
come from the main land, I hurried back, closing the door
behind me to prevent them from entering. The captain,
mate, and my brother seized their rifles, as I did mine,
hoping to kill one or both of the intruders. As we opened the
door, a loud cry uttered by a dog reached our ears. One of
the bears had seized the animal and was carrying him off,
satisfied with his prize. The other was creeping on towards
the hut. Our bullets quickly settled him, and he rolled over.
We then gave chase to the other who was carrying off the
dog, but we were compelled to stop and reload, and by the
time we had done this, so rapidly did the animal run that he
was far beyond our reach, and all hope of rescuing our
canine companion was over. We regretted the loss of the
brave dog. It was a lesson to us not to let the others loose
until we were ready to assist in attacking any similar
visitors. The bear was quickly skinned and cut up. The skin
would serve us for clothing, the fat for fuel, the meat for
food. This visit of the bears showed us that the field of which
our floe formed part must be attached to the land-ice. Our
captain being anxious to visit the shore, intending, should a
favourable spot be found, to form our winter quarters on it—
we agreed to set out the next morning.
The next day we made even less progress than on the first,
though we met with no accident to hinder us. Sometimes we
dragged the sledge over the hummocks, and sometimes we
went round them, the dogs preferring the former method, as
while we toiled they sat up on their tails watching our
proceedings with infinite satisfaction.
“This will do!” cried the mate, “if our shipmates can reach
this, we may pass the winter far better than we should have
done on the open floe.”
The mate was anxious to return at once with the news of our
success, and to guide the party to the shore. He hoped, with
a good night’s rest, to be able to set off early in the
morning, and to perform a great part of the distance before
nightfall.
“Not more than me, sir,” said Sandy; “I’ll go with you, if you
like.”
“No, no, boatswain. You stay and look after the others. You
are older than I am, at all events, and require more rest.”
Saying this the mate went out and closed the door of the
tent.
“After him, lads,” shouted Sandy, but the bear was far too
fleet for us to overtake, and to our grief and dismay
disappeared with his victim behind the rocks to the
northward.
At last I gave in, and Sandy with the seaman set off as soon
as the wind had abated. We watched them as they made
their way over the plain of ice, their forms diminishing into
mere dots, then finally disappearing. We in the meantime
were working away to complete our hut and to render it as
habitable as possible. The flesh of the bear we had killed
afforded us an ample supply of food, while the fat served to
increase our stock of fuel. There was probably drift-wood on
the shore, but except a few pieces which stuck up above the
snow, we could obtain none. We took care of every scrap we
could find, not to burn, but to manufacture into such articles
as we might require. In the crevices of the rocks we
discovered some low creeping plants which in any other
region would have been bushes, but were here a mere
collection of twigs, no thicker than our little fingers, just
appearing above the ground. We agreed that each should
take certain duties, and it was settled that Croil should stay
at home and look after the hut, employing himself in either
cooking or scraping the bear’s skin to make it fit for use as a
covering. Should we kill a sufficient number of bears, we
intended to fasten the skins of some of them together so as
to form a roof to our hut, while others would make great-
coats or bed coverings.
Ewen and I kept under the cliffs and were tempted to make
our way much further south than we had hitherto gone, in
the hopes of discovering some opening into the interior of
the country. We at last reached a part of the cliffs where,
though very rugged, they were less precipitous than in other
parts. The sun was sinking behind them, but we still had
abundance of daylight for exploring. Ewen offered to climb
to the top in the hopes of obtaining an extensive view and
perhaps of finding level ground where we should have the
chance of finding deer or oxen. There was no reason why we
should both run the risk, for a risk there was, though a slight
one.
The two other creatures got closer and closer with the
evident intention of seizing him. I trembled for his safety,
and hurried to the nearest spot from which I could take a
steady aim.
“Never mind the fellow above you,” I shouted. “If you will
shoot the ere nearest to you, I will manage the other, and
we will then tackle the third if he attempts to come down.”
I could well enter into Ewen’s feelings. It was surprising, in
the perilous position in which he was placed, that he should
have retained any presence of mind.
“I wish that we had the sledge to take home the meat and
skins,” observed Ewen, “but we must carry as much as we
can.”
Our fear was that, should we leave the meat, other bears, of
whom there appeared to be a whole colony in the
neighbourhood, would come and devour it. We managed to
get off the skins, which were likely to prove most valuable to
us; and, loaded with them and a portion of the meat, we
returned to the hut, where we found Croil anxiously looking
out for us. He too, had seen a couple of bears moving across
the bay, and was afraid that we might have been attacked
by them, and suffered the fate of the poor mate.
Chapter Eight.
We now waited in anxious expectation for the arrival of our
shipmates, but they did not appear. The days were getting
shorter, the nights longer. The cold was increasing. Often
and often we gazed out over the ice. As far as we could
judge no change had taken place in it. A vast snow-covered
plain, with here and there mountainous heights of ice could
be seen extending as far as the horizon. Unfortunately we
had not brought a telescope, or we thought that we might
have discovered our friends. At length we began to entertain
the most serious apprehensions as to their fate.
We had one evening turned in, and, having closed the door
of the hut, had lighted our lamp and composed ourselves to
sleep, when Ewen roused me up.
“I’ll tell you all about it when we have had some food and
rest. Can you give us something to eat?”
As soon as the meal was over, the two weary travellers lay
down to sleep. Croil imitated their example, while Ewen and
I sat up by the light of the lamp, I mending clothes and my
friend engaged in preparing a small tub for holding bear’s
grease to serve us for fuel. Our conversation naturally took a
melancholy turn. The thought that the floe on which were
my brother and his companions might be dashed to pieces,
and that they would perish miserably, was painful in the
extreme. We thought more of them, indeed, than of
ourselves, though our position was truly perilous. Our only
shelter during the intense cold of an Arctic winter was an ice
hut. Hitherto the bears we had shot had afforded us food
and fuel; but they might take their departure, and we should
then have no other food on which to depend, until the return
of spring should enable us to kill walruses and seals. No
ships, even in the summer, were likely to penetrate so far
north, for few whalers had got so near the pole as the Hardy
Norseman had done, and destruction had overtaken her.
Welcome to our website – the ideal destination for book lovers and
knowledge seekers. With a mission to inspire endlessly, we offer a
vast collection of books, ranging from classic literary works to
specialized publications, self-development books, and children's
literature. Each book is a new journey of discovery, expanding
knowledge and enriching the soul of the reade
Our website is not just a platform for buying books, but a bridge
connecting readers to the timeless values of culture and wisdom. With
an elegant, user-friendly interface and an intelligent search system,
we are committed to providing a quick and convenient shopping
experience. Additionally, our special promotions and home delivery
services ensure that you save time and fully enjoy the joy of reading.
textbookfull.com