Reactive Patterns with RxJS for Angular A practical guide to managing your Angular application s data reactively and efficiently using RxJS 7 Lamis Chebbi - The full ebook with all chapters is available for download now
Reactive Patterns with RxJS for Angular A practical guide to managing your Angular application s data reactively and efficiently using RxJS 7 Lamis Chebbi - The full ebook with all chapters is available for download now
com
OR CLICK HERE
DOWLOAD EBOOK
https://textbookfull.com/product/reactive-programming-with-
rxjs-5-untangle-your-asynchronous-javascript-code-1st-edition-sergi-
mansilla/
textbookfull.com
https://textbookfull.com/product/ng-book-the-complete-guide-to-
angular-nate-murray/
textbookfull.com
https://textbookfull.com/product/angular-up-and-running-learning-
angular-step-by-step-shyam-seshadri/
textbookfull.com
https://textbookfull.com/product/ng-book-the-complete-guide-to-
angular-5-nathan-murray/
textbookfull.com
https://textbookfull.com/product/ng-book-the-complete-guide-to-
angular-9-nathan-murray/
textbookfull.com
https://textbookfull.com/product/ng-book-the-complete-guide-to-
angular-11-felipe-coury/
textbookfull.com
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:
a club, four feet long, until you drive it away, merely watching the
operations of the point of the tail, that, at each blow you give,
thrashes to the right and left most furiously.
‘As the lakes become dry, and even the deeper connecting
bayous empty themselves into the rivers, the alligators congregate
into the deepest hole in vast numbers; and, to this day, in such
places, are shot for the sake of their oil, now used for greasing the
machinery of steam-engines and cotton mills, though formerly, when
indigo was made in Louisiana, the oil was used to assuage the
overflowing of the boiling juice, by throwing a ladleful into the kettle
whenever this was about to take place. The alligators are caught
frequently in nets by fishermen; they then come without struggling
to the shore, and are killed by blows on the head given with axes.
The zoology of the United States opens a wide and interesting field of
observation: it is more peculiar and striking than either the mineralogy or
botany. The following general view of the mammiferous animals inhabiting
North America is given by Dr. Harman. The number of species now
ascertained is one hundred and forty-six, in which we do not include man;
of these twenty-eight are cetacea, and one hundred and eighteen are
quadrupeds. Among the quadrupeds, Dr. Harman reckons eleven species, of
which no living trace is found in any part of the world; which cannot of
course be considered as forming a part of our present zoology. The number
of living species of quadrupeds is therefore one hundred and seven. The
comparative numbers of the several orders are stated as follows, omitting
man:
Carnivora 60
Glires 37
Edentata 6
Pachydermata 2
Ruminantia 13
Cetacea 28
Species.
1 Mole.
2 Shrew.
1 Bear.
1 Glutton.
1 Otter.
2 Wolf.
2 Fox.
2 Seal.
2 Weasel.
1 Beaver.
1 Field-mouse.
1 Campagnol (rat.)
1 Squirrel.
2 Deer.
1 Sheep.
Charles Lucien Bonaparte has arranged the birds of the United States in
twenty-eight families, eighty-one genera, and three hundred and sixty-two
species, viz.: two hundred and nine land, and one hundred and fifty-three
water-birds. Of the eighty-one genera, sixty-three are common to Europe
and America, while eighteen have no representatives in Europe.
CHAPTER XVII.—
BOTANY.
The vegetation of the United States is as various as the climate
and soil. In Florida and the southern states, the superb magnolia,
the majestic tulip tree and the deciduous cypress charm the traveller
by their grandeur and beauty. The lofty oak, the stately fir and the
gracefully-waving elm of the north, present a different and still a
highly interesting study to the naturalist. As a general observation,
the trees of the United States are larger, taller, and more generally
useful for timber than those of Europe. As to height, it is observed
by Michaux, that, while in France only thirty-seven species of trees
arrive at thirty feet, in the transatlantic republic, one hundred and
thirty exceed that elevation. A general idea of the American forest
having thus been given, we will now notice, as largely as our limits
will permit, the most remarkable trees.
Of all the American oaks, this is the best and the most generally
used, being strong, durable, and of large dimensions. It is less
employed than formerly in building, only because it is scarcer and
more costly. Among the uses of this wood, the most important is in
ship-building. In all the dock yards of the northern and middle
states, except Maine, it is almost exclusively employed for the keel,
and always for the lower part of the frame and the sides: it is
preferred for the knees, when sticks of a proper form can be found.
In the smaller ports south of New York, the upper part of the frame
is also made of white oak; but such vessels are less esteemed than
those constructed of more durable wood. The medicinal properties
of oak bark depend on its astringency, and that again on its tannin.
The inner bark of the small branches is the strongest, the middle
bark next, and the outer bark is almost useless.
The Gray Oak, Water Oak, Bear Oak, Upland, Willow Oak, and
Bartram Oak are interesting varieties. The Laurel Oak is a stranger
north of Philadelphia, and is rare in the more southern states. It is
most abundant in the open savannas of Illinois. Rising to the height
of forty or fifty feet, clad in a smooth bark, and for three fourths of
its height laden with branches, it presents an uncouth appearance
when bared by the winter blasts, but in the summer with its thick
tufted foliage is really beautiful. The Black Oak is found throughout
the country, with the exception of the northern part of New England.
It is one of the loftiest of the American forest trees, rising to the
height of eighty or ninety feet, with a diameter of four or five feet.
The wood is reddish and coarse-grained, with empty pores, but is
esteemed for strength and durability. It furnishes excellent fuel, and
the bark is largely used for tanning. Other varieties of the oak are
numerous.
When the wood of this tree is freshly cut, the sap is white and
the heart of a violet color, which, after a short exposure to the air,
assumes an intenser shade, and becomes nearly black: hence
probably is derived the name Black Walnut. There are several
qualities for which its wood is principally esteemed: it remains sound
for a long time, even when exposed to the influences of heat and
moisture; but this observation is only applicable to the heart, the sap
speedily decays: it is very strong and very tenacious: when
thoroughly seasoned, it is not liable to warp and split; and its grain
is sufficiently fine and compact to admit of a beautiful polish. It
possesses, in addition to these advantages, that of being secure
from worms. On account of these excellencies, it is preferred and
successfully employed in many kinds of work. East of the
Alleghanies, its timber is not extensively used in building houses,
but, in some parts of Kentucky and Ohio, it is split into shingles
which serve to cover them: sometimes also this timber enters into
the composition of the frame. But it is chiefly in cabinet-making, that
this wood is employed wherever it abounds.
Maple.—The Sugar Maple, called also rock maple, has leaves five-
parted, and yellowish green flowers, and is one of the loftiest trees
in our forests. Its trunk is usually straight and entire, to the height of
from forty to eighty feet, where it suddenly unfolds into a dense top,
crowded with rich foliage. The bark of the older trees is gray, and
marked with numerous deep clefts. The wood is firm and heavy,
though not durable. It is much used by cabinet-makers, and when
cut at the right season forms excellent fuel. Michaux says, that it
grows in its greatest perfection, between the forty-third and forty-
sixth degrees of north latitude.
Among the resinous trees of the United States, the White Cedar
is one of the most interesting for the varied utility of its wood. North
of the river Connecticut, it is rare and little employed in the arts. In
the southern states, it is not met with beyond the river Santee, but it
is found, though not abundantly, on the Savannah: it is multiplied
only within these limits and to the distance of fifty miles from the
ocean. The white cedar is seventy or eighty feet high, and
sometimes more than three feet in diameter. When the trees are
close and compressed, the trunk is straight, perpendicular and
destitute of branches to the height of fifty or sixty feet. When cut, a
yellow transparent resin of an agreeable odor exudes, of which a
few ounces could hardly be collected in a summer from a tree of
three feet in circumference. The foliage is evergreen: each leaf is a
little branch numerously subdivided, and composed of small, acute,
imbricated scales.
The White Beech is one of the tallest and most majestic trees of
the American forests. It grows the most abundantly in the middle
and western states. On the banks of the Ohio, the white beech
attains the height of more than one hundred feet, with a
circumference of eight to eleven feet. In the forests, where these
trees vegetate in a deep and fertile soil, their roots sometimes
extend to a great distance even with the surface, and being
entangled so as to cover the ground, they embarrass the steps of
the traveller and render the land peculiarly difficult to clear. This tree
is more slender and less branchy than the red beech; but its foliage
is superb, and its general appearance magnificent.
The Bow Wood is a very striking tree, found about the upper
courses of the Washita, the middle regions of Arkansas, and
occasionally on the northern limits of Louisiana. Its leaves are large
and beautiful, and its fruit, which somewhat resembles a large
orange, is of a most inviting appearance, but is ‘the apple of Sodom
to the taste.’ It is considered by many the most splendid of all forest
trees.
The China Tree is much cultivated in the south-western region of
the states, as an ornamental shade tree. Its leaves are long and
spiked, set in correspondence on each side of the stem. The verdure
is deep and brilliant. When in full flower, the top is one tuft of
blossoms. The tree is of most rapid growth, and its beautiful color
imparts delightful freshness to the landscape. After the fall of its
leaves, a profusion of reddish berries remain, and give at a little
distance the appearance of continuing in flower. This berry is a
narcotic, and stupefies the birds that eat of it.
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