Instant ebooks textbook Reactive Patterns with RxJS for Angular A practical guide to managing your Angular application s data reactively and efficiently using RxJS 7 Lamis Chebbi download all chapters
Instant ebooks textbook Reactive Patterns with RxJS for Angular A practical guide to managing your Angular application s data reactively and efficiently using RxJS 7 Lamis Chebbi download all chapters
com
OR CLICK BUTTON
DOWNLOAD NOW
https://textbookfull.com/product/reactive-programming-with-
rxjs-5-untangle-your-asynchronous-javascript-code-1st-edition-sergi-
mansilla/
textboxfull.com
https://textbookfull.com/product/ng-book-the-complete-guide-to-
angular-nate-murray/
textboxfull.com
https://textbookfull.com/product/angular-up-and-running-learning-
angular-step-by-step-shyam-seshadri/
textboxfull.com
https://textbookfull.com/product/ng-book-the-complete-guide-to-
angular-5-nathan-murray/
textboxfull.com
https://textbookfull.com/product/ng-book-the-complete-guide-to-
angular-9-nathan-murray/
textboxfull.com
https://textbookfull.com/product/ng-book-the-complete-guide-to-
angular-11-felipe-coury/
textboxfull.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
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.
Other documents randomly have
different content
CAPITOLO III.
In viaggio.
*
* *
A chi conobbe Alfredo Ferretti, direttore dell’Odine, uomo abilissimo,
consumato in tutti gli intrighi, esperto diplomatico all’occorrenza, il di
lui contegno tenuto di fronte a Giuliano potrebbe sembrare strano,
tanto più che spesso ambiva guadagnarsi gli uomini onesti colla
simpatia. Ferretti non poteva illudersi sull’effetto prodotto nell’animo
del suo nuovo pupillo, la nuova vittima abbandonatagli, piedi e mani
legati, dal commendatore Cerasi.
Era calcolato! Ferretti, con un’affettazione esagerata di cinismo, volle
prevenire tutto il male che sarebbe stato detto di lui al giovine
cliente milionario. Passata la prima impressione, Giuliano, lo avrebbe
trovato migliore della sua fama.
D’altronde, in quell’uomo audace c’era dell’amore dell’arte per l’arte,
e qualche volta provava una specie di voluttà nell’atteggiarsi sotto il
punto di vista peggiore. Potente, sentiva una soddisfazione maligna
nell’umiliare i galantuomini, dei cui destini tanto spesso era arbitro.
Per l’uomo colpito dal pubblico disprezzo, eran vendetta e trionfo i
rovinosi compromessi degli ambiziosi, ingenui o raffinati, che a lui
facevan capo, guida inevitabile per forzare le consegne dei ministeri,
per arrivare al cuore della insospettabile magistratura giudiziaria, su
su, fino alla Corte di cassazione, al guardasigilli, per giungere ad
intenerire gli alti controlli, la Corte dei conti, il Consiglio di Stato.
Per lui, il colpito, non una porta chiusa, non serrature abbastanza
resistenti: dagli sportelli delle banche agli uffici dei giudici istruttori,
ai gabinetti delle eccellenze d’ogni sorta e qualità, fin nella coscienza
dei giurati. Munito di non si sa qual talismano, avrebbe fatto crollare
le mura del più inaccessibile castello incantato, come già seppe
aprire breccie perfin nelle muraglie dell’inviolabile Vaticano, il quale
non sapendo sottrarsi ai di lui ricatti, aveva finito per arrendersi,
preferendo amico, possibilmente strumento, un sì pericoloso
avversario.
Fu allora che l’Ordine si atteggiò protettore della religione, avvocato
di un modus vivendi, inattuabile, tra Vaticano e Quirinale. La
clientela de’ sacerdoti non fu la meno numerosa e profittevole.
Consigliere ascoltato in tutte le operazioni finanziarie, lo si additava
cogli autori del crack vaticanesco; vittima la corte pontificia della crisi
bancaria, nella quale fu travolta mezza Italia.
Ferretti, per quanto forte lottatore e calcolatore insuperabile, aveva
finito per ubriacarsi della propria potenza; onde, l’eccessiva audacia,
il supremo disprezzo di ogni riguardo, di ogni concessione alle
apparenze, dirò meglio, di ogni impostura verso gli onesti o
disonesti, deboli o potenti che a lui mettevano capo.
Avido di lucro, era il più abile cacciatore al biglietto di banca,
coglieva i fogli da mille a volo, meglio di Buffalo Bill al galoppo del
suo cavallo le palle di creta lanciate in aria.
Senza mischianza di sangue orientale, nell’audacia superava i più
forti giuocatori semiti. Pazzamente temerario, in borsa aveva dieci
volte ammassato cospicui patrimonî, con eguale rapidità disfatti. La
rassomiglianza ebraica rivelavasi ancora nel suo sistema di lottare
per la vita... per il milione; ai mezzi semplici preferiva i complicati e
subdoli; alla via retta, la tortuosa, creando sovente ostacoli che non
esistevano, per la soddisfazione, la gloria di superarli.
Nei primi anni di lotta, la lotta per la riabilitazione, aveva saputo
anche spendere intelligentemente, a tempo. Creditore di una miriade
di bohèmes, si era creato un ambiente, se non amico, benevolo,
discreto, servile.
Non tollerava emuli; accettava alleati, sui quali lasciava cadere
magnanimamente un po’ del riflesso della sua onnipotenza.
Un nemico odiato a morte, un uomo piccolo, come lui, che, come lui,
aveva esordito dalla carcere, per motivi non politici, s’intende, il
quale di venticinque anni più di lui attempato, e più di lui orientale,
era completamente riuscito. Vittorioso sempre, sterminatamente
ricco, potente senza vanità ed affettazione, eminenza grigia di tutti i
governi di Sinistra.
Quell’uomo era l’incubo di Ferretti, il solo del quale avesse paura.
E poi, nelle ore tristi, quaudo la marea del disgusto gli saliva al
cervello, per la coscienza della propria abiezione, in presenza di
persone adorate, che avrebbe voluto mettere al livello morale di ogni
onesta famiglia borghese, lo invadeva un sentimento di invido furore,
nel vedere il nemico, l’odiato competitore, stimato e rispettato,
additato come esempio di patriotismo disinteressato o sapiente.
Era la spina in cuore.
Nel tenebroso duello quale dei due rimarrà sconfitto?
L’orientale combatteva dietro gli spalti del silenzio, invulnerabile,
lontano dalle polemiche, alieno dal chiasso, dopo una imprudente,
trista prova di pubblicità in favore della politica germanica, dopo lo
scandalo di certi appalti governativi, che per poco non provocarono
una crisi ministeriale. L’orientale evitava porgere il fianco, preferendo
lasciar combattere per lui i suoi mercenarî e gli amici, gli ammiratori
ingenui; un esercito.
L’orientale, Augusto Dini, doveva vincere necessariamente. Lo
sentiva Ferretti? È probabile, perchè aveva paura, lui, l’audace, il
Bajardo, il Sans peur dei farabutti.
Altro lato debole: le antiche abitudini nottambule, la passione del
gioco. È ben vero che Ferretti vinceva sempre; ma, le notti perdute
vincendo al tavolino verde dovevano necessariamente infiacchire la
fibra del lottatore, per quanto d’acciajo.
Questo l’uomo al quale l’ingenuo Giuliano affidava il suo avvenire
politico.
*
* *
Puntuale al convegno, Ruggeri, a mezzogiorno in punto, l’ora
convenuta per la colazione, bussava all’uscio del salotto n. 11
dell’albergo del Quirinale.
Giuliano, tuttavia sotto l’impressione disgustosa provocata
dall’intervista con Ferretti, avrebbe voluto fingere coll’amico, per non
dargli causa vinta di primo acchito; ma fingere non sapeva. I suoi
occhî azzurri erano impregnati di malinconia, aumentata dai ricordi
d’amore evocati nella sua lettera alla sposa lontana. Se avesse osato,
in quel momento avrebbe rinunziato alla deputazione; ma, di
risoluzioni energiche non era capace. Il ritorno immediato alla vita
privata sarebbe stata la vittoria degli avversarî, de’ suoi detrattori;
una diserzione, di fronte agli amici che lo avevano sostenuto. Il dado
era tratto! Si sarebbe ritirato poi, come fece Ruggeri, nobilmente, al
primo atto meno corretto del Governo, ai cui servigi si era posto. Ora
bisognava vincere e per vincere andar fino in fondo.
Ruggeri aveva indovinato lo scoraggiamento dell’amico, pure gli
sarebbe sembrato sconveniente insistere nei rimproveri del mattino.
D’altronde, egli nulla sapeva della visita al famigerato Ferretti,
quindi, a poco a poco, la loro conversazione divagò su tutt’altri
soggetti della politica.
Miralto, la monotona, triste, uggiosa Miralto; egualmente cara a
Ruggeri, sorridente ricordo di giovinezza, cara ad onta di dolorose
memorie. Là riposano i suoi vecchî; là vivono, anzi vegetano,
relativamente felici, gli antichi compagni d’infanzia, minuscoli
cospiratori contro l’Austria odiata; là i primi palpiti dell’ormai spento
patriotismo e i santi entusiasmi. Di là, in una notte buja, l’esodo per
il Piemonte, terra di libertà, onde correre alle armi per la redenzione
della patria.
Ruggeri, ricordando tutto ciò, il misantropo Ruggeri ringiovaniva, e
narrava con eloquenza commossa cose ed episodî cento volte
raccontati a Giuliano quando questi, bambino, sulle di lui ginocchia,
cogli occhi azzurri intenti, entusiasmavasi alle lacrime per i sublimi
ardimenti di Garibaldi.
Servito il caffè ed il cognac, i solleciti camerieri discretamente si
ritirarono... Sovvennero le ricordanze più intime. Nel benessere della
digestione di un asciolvere eccellente, i gomiti sulla tavola,
centellinando la fine champagne, alternata col fumo delle sigarette
orientali, l’uno, il vecchio, discorreva entusiasta; l’altro, quantunque
soggiogato dal fascino dell’eloquenza calda del suo interlocutore,
freddo, riservato, meravigliava alla di lui foga giovanile. Concepito al
tuonare delle artiglierie, ma ingrandito quando gli entusiasmi erano
sbolliti, quando, riconquistata una patria, gli uomini assennati si
apprestavano a divorarla, quando i fanciulli, credendo l’opera della
redenzione compiuta, consideravano la politica mezzo ad accelerare
la carriera, nuova carriera essa stessa, la carriera, sola
preoccupazione della nuova generazione, sola meta, Giuliano
meravigliava.
La fiamma del sagrificio si è spenta colle delusioni del 1866 e col
facile trionfo di Porta Pia. L’uno era davvero l’uomo del passato;
l’altro, educato alla scuola positivista, sarebbe stato del suo tempo,
se la natura l’avesse meglio costituito per la lotta; alla lotta incapace
per la fibra molle, per la gentilezza femminea degli istinti.
E Ruggeri, quasi fosse in tale ordine di idee, a soggiungere:
— Certo il patriotismo è un pregiudizio, municipalismo ingrandito, un
pregiudizio di fronte al sentimento umanitario, che vorrebbe una sola
famiglia nella umanità, una sola patria sul pianeta Terra; ma, per noi,
era la nostra fede, era una religione, la sola nostra religione, co’ suoi
profeti ed apostoli, i suoi martiri, i suoi eroi. Che cosa rimane di
ideale a voi? L’amore? Anch’esso è mutato, spogliato del
romanticismo sentimentale, un po’ mistico, nel quale noi
l’avvolgevamo. Anche oggi si ama; anche oggi si muore d’amore, ma
di Werther e di Jacopo Ortis non ne nascono più. Si ama altrimenti.
Giuliano avrebbe voluto soggiungere per provare che i Werther sono
assurdi e ridicoli gli Ortis; rispettò il silenzio dell’amico, che, d’un
tratto, si era taciuto, appoggiando il capo fra le mani, in
atteggiamento di sconforto profondo.
Dopo un istante, Ruggeri, surto da sedere e passeggiando concitato
per l’angusto salotto, rivoltosi sorridente all’amico:
— Sono un vecchio pazzo. Fortunati voi altri che non avete tante
fisime per la testa. Più pratici, valete meglio di noi, incontentabili
brontoloni... A proposito, sai che ora è? Le tre! Nientemeno. Tre ore
a tavola al mattino, non c’è male; io ti lascio... A domattina,
adunque: non dimenticare la colazione a Belvedere.
Giuliano, rimasto solo, scotendo il capo mormorò:
— Povero Ettore!
E dopo breve pausa:
— Povera Stella!
*
* *
Stella Gabelli è la fanciulla che appena abbiamo intraveduta a
Miralto, compagna alla contessa Adele Sicuri, inseparabile amica.
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