Reactive State for Angular with NgRx
eBook - ePub

Reactive State for Angular with NgRx

Learn to build Reactive Angular Applications using NgRx (English Edition)

  1. English
  2. ePUB (mobile friendly)
  3. Available on iOS & Android
eBook - ePub

Reactive State for Angular with NgRx

Learn to build Reactive Angular Applications using NgRx (English Edition)

About this book

Learn how to build a Reactive Application with Ngrx and Angular Key Features

  • Learn how to create your own minimalistic Redux implementation.
  • Get familiar with the working of NgRx Store.
  • Learn how to handle asynchronous events without breaking Redux paradigm using NgRx Effects.
  • Learn how to manage router state using NgRx Router Store.
  • Deal with a list of records using an entity state adapter pattern using NgRx Entity.

  • Description
    This book will help you learn NgRx in and out. We will start by discussing the fundamental ideas that underpin the design for the centralized store and the need for state management in Angular. We will then learn about the Redux paradigm and the three rules it governs. Along the way, we will explore various Redux terminologies in terms of action, dispatcher, and reducer and will then create our minimalistic version of Redux. We will have a dedicated chapter that paves the way for an Angular application in which we will be integrating NgRx throughout the book. We will also work with Redux Devtools, which will be crucial to debugging NgRx. The book also focuses on the creation of the NgRx Store using @ngrx/schematics and hooking it up in the sample Angular application we built previously. Till here, the sample Angular application is purely relying on NgRx to read/write the application state except for the router state. Next, we will leverage the NgRx Router Store to bring the router state under the radar of NgRx as well so that the entire sample Angular application would be using a single source of truth in terms of NgRx for any application data. Towards the end, we will optimize the list of records using a proven entity state adapter pattern via NgRx Entity to interact with such records at the individual level to be efficient and performant. What will you learn
  • Learn the fundamentals of State Management.
  • Learn how NgRx works under the hood and make your Angular applications truly reactive.
  • Learn how to handle asynchronous events with NgRx Effects.
  • Learn how to use record collection using NgRx Entity.
  • Learn advanced Angular application using Angular/Material/NgRx/RxJS/TypeScript.
  • Get acquainted with the knowledge to understand any other state management library.

  • Who this book is for
    Beginners, as well as Experienced Angular developers who want to write sustainable Angular applications over time, will benefit from this book. This book is for anyone interested in State Management with NgRx in Angular. Table of Contents
    1 Redux Principles for ROCK solid application state
    2 Setting up NgRx in Angular
    3 NgRx Store
    4 NgRx Effects
    5 NgRx Router Store
    6 NgRx Entity State About the Authors
    Amit Gharat is a full-stack engineer and open source contributor. He has built many personal projects in AngularJS/Angular and made some of them open source as well, such as directives, SPAs, and chrome extensions. He was fortunate to write AngularJS UI Development and AngularJS Directives in Traction (unpublished) back in 2015 for two of the largest UK based publishers. He has an excessive urge to share his programming experiences in an easy-to-understand language through his blog (http://amitgharat.wordpress.com). When not programming, he enjoys reading science-fiction, watching movies, and playing games on his brand new Playstation 4 Pro. This is his 3rd book. Your LinkedIn Profile: https://www.linkedin.com/in/amitgharat/

Trusted byĀ 375,005 students

Access to over 1 million titles for a fair monthly price.

Study more efficiently using our study tools.

Information

Year
2020
eBook ISBN
9789389898248

CHAPTER 1

R.O.C.K. Solid Application State

You may have kept a phone aside or turned off a Smart TV to solely focus on reading this chapter on your kindle or laptop. That means you have successfully transitioned from one state of being to another. However, we often deal with such different states on a daily basis by performing various actions without paying much attention, via our subconscious mind. Sometimes we multitask as well; that is dealing with multiple states at the same time like singing while driving. And whether you can seamlessly do all the tasks at hand is all controlled by your mind. For that very reason, you end up asking your mind to recall where you had kept the car keys last time even though it’s your hand that threw those keys somewhere in the living room. You purposefully do not ask your hand and instead scan your brain to recall the last snapshot of the car keys in the living room under the sofa because the brain is in charge of every action you perform. It tracks the outcomes of every action and uses them as the experience to perform the next action adroitly.
Now imagine, you are not a human being but a Single Page Application (SPA) written in JavaScript and running in a browser and a higher-level-energy in terms of a user is guiding you to change the world, probably the VM world. So throwing off the car keys is called Action, the eyes who are letting the brain know about the action being performed is called Dispatcher, reconciling the outcomes of the event i.e. where the car keys had landed in the living room is a job of Reducer, and the brain where we store the memory of the event in order to recall later using Selector is called Application State.
In this chapter, you will learn to recognize your application state and make it R.O.C.K. solid using Redux principles. Using the simplest form of a shopping cart as an example, we will organize its application state and tame it in such a way that it will become scalable and maintainable as the application grows in the future.

Structure

After a bird's eye view of Application State and Redux jargons above, we will discuss the following topics in great detail in this chapter:
  • Application State in Angular
  • The Three Musketeers of Redux

Objectives

In this chapter, you will explore some fundamental ways of thinking about the application state using Redux principles. These principles will guide us through the rest of the book, where we dive into deep technical detail. Along the way, we will create our minimalistic version of NgRx to know the intricacies.

Application State in Angular

You may have already dealt with an application state in your personal or private projects in the form of scattered data lying across the application inconsistently. Instead of treating the application state as a passive variable that is manipulated by the application, it is ideal for an application to respond to state changes in one place by triggering state changes in another place. The interplay and collaboration between state, state changes, and the code that processes them is called State Management. The state management libraries have come up with a way to group the distributed states into a centralized store under the umbrella term called Application State. So the application state is nothing but local static data, server responses, cached data, and more in the form of JSON or primitive types that drive the application behavior. The same application could then mutate the associated state when certain changes are propagated by the users of the application such as agreeing to the terms and conditions by clicking on a checkbox, completing registration by hitting the submit button, selecting a tab, pagination controls, and so on. With this notion, it is safe to assume that any kind of data backing the application can be a part of the global Application State.
Figure 1.1 shows the visualization of Redux architecture (Side-effects a.k.a. Redux Effect is excluded to simplify the understanding, which we’ll cover in Chapter 4: NgRx Effects). A component dispatches the action and the reducer acts upon the said action to spit a brand new application state in order to store it in the centralized store. Then, the component subscribes to the state changes using the selector to update the parts of the view:
Figure 1.1: Birds-eye view of Redux
To understand the big picture and how these pieces come together, we’ll create a very simple Angular application next. Let us look at a Dead Simple Shopping Cart Application in Angular in Figure 1.2:
Figure 1.2: Dead Simple Shopping Cart Application in Angular
Here (https://bit.ly/bpb-129) is the sample code for the above application. It is recommended to fork it and update the same as we move along each section.
In this application, we have a static list of products stored in a component class, which is then rendered in a component template via the ngFor directive. Additionally, we can add the individual product into a cart by clicking the Action button. If we try to apply the learned Redux terminology to this example then the products property is the application state that is driving our UI. We then mutate the individual product to mark the addedToCart property to true when the product is added to the cart. Below is the app/product-list/product-list.component.ts component for your perusal:
import {Component, OnInit} from ā€˜@angular/core’;
@Component({
selector: ā€˜app-product-list’,
template: `
<h2>Products</h2>
<div *ngFor=ā€let product of products; let i = indexā€>
<h3>{{i + 1}}. {{product.name}}</h3>
<button (click)=ā€addToCart(i)ā€
[textContent]=ā€product.addedToCart ? ā€˜Added to Cart’ : ā€˜Add to Cartā€™ā€>
</button>
</div>
`
})
export class ProductListComponent implements OnInit {
public products;
ngOnInit() {
this.products = [
{name: ā€˜Laptop Air’, price: 799, addedToCart: false},
{name: ā€˜Laptop Pro’, price: 699, addedToCart: false},
{name: ā€˜Laptop Mini’, price: 299, addedToCart: false}
];
}
addToCart(i) {
this.products[i].addedToCart = true;
}
}
By the sheer look at the code, the Angular component is doing what it is supposed to do and our teeny-tiny Angular application looks just fine, probably the best-written code ever. However, it will blow up when it grows with lots of features and functionalities such as remove-from-cart button, bidding on price, product customizations, payment gateway integration, order tracking, etc. And the reason that the current approach is not scalable is because it has issues (which we will learn more about to fix them going forward), although not so evident at this point which is what brought us to Redux.

The Three Musketeers of Redux

Redux, in its simple language, is a predictable state container a.k.a. centralized store in the form of a JSON object for JavaScript applications that will allow us to manage our application state seamlessly with less boilerplate code. Building a large Angular application has its problems when it comes to managing the application state which is humongously big and complex. It is highly likely in such a complex application that one view updates a model which will affect another view, which, in turn, updates another model to change some other view. And after a while, we’ll lose track of which view is updating which model and affecting which other view - it is a downward spiral. Redux makes it easy for applications to read and write states consistently and without any side-effects. It does so consistently because every model change must dispatch an action, that is, notify the centralized store first. Then, Redux takes care of making the necessary mutations to the s...

Table of contents

  1. Cover Page
  2. Title Page
  3. Copyright Page
  4. Dedication Page
  5. About the Author
  6. About the Reviewers
  7. Acknowledgement
  8. Preface
  9. Errata
  10. Table of Contents
  11. 1. R.O.C.K. Solid Application State
  12. 2. Setting up NgRx in Angular
  13. 3. NgRx Store
  14. 4. NgRx Effects
  15. 5. NgRx Router Store
  16. 6. NgRx Entity State

Frequently asked questions

Yes, you can cancel anytime from the Subscription tab in your account settings on the Perlego website. Your subscription will stay active until the end of your current billing period. Learn how to cancel your subscription
No, books cannot be downloaded as external files, such as PDFs, for use outside of Perlego. However, you can download books within the Perlego app for offline reading on mobile or tablet. Learn how to download books offline
Perlego offers two plans: Essential and Complete
  • Essential is ideal for learners and professionals who enjoy exploring a wide range of subjects. Access the Essential Library with 800,000+ trusted titles and best-sellers across business, personal growth, and the humanities. Includes unlimited reading time and Standard Read Aloud voice.
  • Complete: Perfect for advanced learners and researchers needing full, unrestricted access. Unlock 1.4M+ books across hundreds of subjects, including academic and specialized titles. The Complete Plan also includes advanced features like Premium Read Aloud and Research Assistant.
Both plans are available with monthly, semester, or annual billing cycles.
We are an online textbook subscription service, where you can get access to an entire online library for less than the price of a single book per month. With over 1 million books across 990+ topics, we’ve got you covered! Learn about our mission
Look out for the read-aloud symbol on your next book to see if you can listen to it. The read-aloud tool reads text aloud for you, highlighting the text as it is being read. You can pause it, speed it up and slow it down. Learn more about Read Aloud
Yes! You can use the Perlego app on both iOS and Android devices to read anytime, anywhere — even offline. Perfect for commutes or when you’re on the go.
Please note we cannot support devices running on iOS 13 and Android 7 or earlier. Learn more about using the app
Yes, you can access Reactive State for Angular with NgRx by Amit Gharat in PDF and/or ePUB format, as well as other popular books in Computer Science & Software Development. We have over one million books available in our catalogue for you to explore.