Datastore in Angular

Sophia Zhang
9 min readNov 30, 2023

--

State Machine — MidJourney

Why we need a datastore?

In Angular applications, a datastore is essential for managing state effectively, filling the gap between the stateless nature of functional programming and the dynamic needs of front-end applications. Angular relies on the functional approach using, for example, the observable pattern. It emphasizes processes and transformations over storing state. Such an approach requires developers to find state management solution for maintaining data consistency across multiple components.

The NGRX datastore enables the storage and synchronization of the application’s state at the global level. This ensures that all components have access to the up-to-date state, resulting in the smoother user experience and making developers’ life easier in state management across the application’s lifecycle.

This blog post will mainly focus on:

  • The structure of NGRX datastore
  • Managing state using datastore
  • Visualizing datastore
  • Using the datastore for managing API requests
  • Insights on build a scalable datastore

1. The structure of NGRX datastore

Let’s have a look at a simple example in which a front-end component interacts with the backend service and the local datastore.

The black path illustrates the local front-end state changes, while the red path indicates the interaction with the backend — both update the state of the store. We focus on these flows in this section. The purple path is a read from the datastore and is covered in the next section.

This workflow diagram shows how different parts interact with the actual Store, which is the heart of the NGRX architecture that holds all the state of the application. Let’s look at the purpose of other parts.

Selectors are used by the application to get specific data from the store. Think of queries for databases, of sorts.

Actions tell the other components (such Reducers, Effects, and eventually the Store) what needs to be done, e.g., add a book to a collection, remove or update an item on the backend, etc.

Reducers decide how the state should change in response to an action. They are pure functions: they take both the current state and the action and return a new state. They have no state of their own.

Effects handle side effects, e.g., making API requests or receiving events via web sockets. They listen for actions, perform their task, and then dispatch new actions (and eventually to reducers and the store) based on the task’s results.

All read operations follow the same purple path: we use a selector to choose data we need from the Store by providing the names of the data resources we wish to select.

The write operations are more complicated and flexible. Red and black paths represent two common data write flows in the datastore (numbers indicate the order of execution):

Black Path — Front-end State Management, with no backend interaction:

  1. A component dispatches an action (like Add Book).
  2. The action goes to a reducer.
  3. The reducer decides how to update the state.
  4. The updated state is stored in the store.

Red Path — Backend Interaction:

  1. A component dispatches an action (like Fetch Data from Server).
  2. The action triggers an effect.
  3. The effect uses a service to interact with the database.
  4. Once the data is fetched, the effect dispatches a new action (like Data Fetch Succeed).
  5. This action goes to a reducer.
  6. The reducer updates the state based on this new data.
  7. The updated state is stored in the store.

2. Managing state using datastore

Let’s dive into a hands-on demo of how these components interact in the code. This section will cover the NgRx datastore read operations (the purple path) and write operations (the black path) in the image below.

The wish list page is a good starting point for a bookstore:

Imagine you are developing a bookstore web application where you need to collect information about the books users intend to buy. In the following part of the blog, we will build a basic wish list page for a bookstore, utilizing the NGRX datastore structure.

Let’s start by constructing the wish list submission form:

// Wish list form
<form myform="ngForm" ngSubmit="addBook(myform)" autocomplete="off">
<div class="form-group">
<label for="id">id</label>
<input
type="text"
class="form-control"
name="id"
id="id"
ngModel="bookFormId$ | async"
required
/>
</div>
<div class="form-group">
<label for="author">Author</label>
<input
type="text"
class="form-control"
ngModel
name="author"
id="author"
required
/>
</div>
<div class="form-group">
<label for="name">Book Name</label>
<input
type="text"
class="form-control"
ngModel
name="name"
id="name"
/>
</div>
<div class="form-group">
<label for="type">type</label>
<input
type="text"
class="form-control"
ngModel
name="type"
id="type"
/>
</div>
<button type="submit" class="btn btn-primary">Submit</button>
</form>

When a user clicks the Submit button, we want to record their submission into the datastore. Following the flow mentioned before, we need to define and fire the Add_Book action when the user submits the wishlist form:

Define Actions

export enum BookActionType {
Add_Book = '[Book] Add Book',
}

export class AddBookAction implements Action {
readonly type = BookActionType.Add_Book;
//add an optional payload
constructor(public payload: BookItem) {}
}

Dispatching Actions

// Dispatch an action to add a new Book
addBook(form: NgForm) {
this.store.dispatch(new AddBookAction(form.value));
form.reset();
}

Now we need to register a reducer that listens for the Add_Book action and updates the store accordingly (adds a new book to the existing wish list):

Reducers

// Example BookReducer
const BookReducer = (state, action) => {
switch (action.type) {
case BookActionType.Add_Book::
return { ...state, books: [...state.books, action.payload] };
// Handle other actions here
default:
return state;
}
};

Users want to see their wish lists. For that we use selectors to read data from the datastore.

Reading State

// Display the books in the wish list 
<div class="col-md-12">
<h4>Book wish list - NGRX demo</h4>
</div>
<div class="col-md-6">
<ul class="list-group">
<li class="list-group-item" ngFor="let Book of bookItems$ | async">
<b>{{ Book.author }} - {{ Book.name }}</b> - ( {{ Book.type }} )
</li>
</ul>
</div>

// Select the "books" state from the store
ngOnInit(): void {
this.bookItems$ = this.store.select((store) => store.books);
this.bookFormId$ = this.store.select(
(store) => store.books[store.books.length - 1].id + 1
);
}

So far, we have implemented a book wishlist application using the NGRX datastore. It can add new book to wishlist and read the existing ones.

Now, let’s bring all these pieces together and see how the application functions. You can access the repository of this project by clicking on this link.

If everything is configured correctly, you should be able to observe something similar to the video below:

3. Visualizing datastore

A debugger is your friend when you’re developing something complex. Redux visualization tool provides you an easy GUI to check what action has been fired and what data has been put into the store. I highly recommend using it instead of sifting through the massive console log output.

To install, use the npm package manager:

npm install @ngrx/store-devtools

Then, configure it in the app.module.ts file to ensure it’s correctly imported:

imports: [
... // all the previous import statement
StoreDevtoolsModule.instrument({
maxAge: 25, // config the maximum number of actions stored in the history tree
}),
]

Once you’ve completed the above steps, you should be able to access the Redux visualization tool in your browser’s developer tools and observe the following:

4. Using datastore for managing API requests

So far we have the NGRX data store working and have the right tool for monitoring. The datastore can bring backend data closer to the web application. By storing API call results in it, we have a centralized location for all the state data in our application. This section covers the datastore write operations marked by the red path in the image below.

NGRX effects handle async requests to backend APIs and pass the results to reducers. They listen for actions triggered by the application, similarly to reducers. The difference is that the reducers are pure functions responsible for updating the application state based on dispatched actions (such as success or failure actions from NGRX effects).

In the current version of our web app, BookReducer captures the Add_Book action from the form and adds the new book data to the datastore. Now we want to make an API request to the backend and update the datastore depending on the response from the server.

For that, our new effect will listen to the Add_Book action (instead of BookReducer), call the backend, and issue a new action, Success. The BookReducer will listen to this new action and update the Store.

The following code section implements the updated data store design.

Create an Effect: Define an NGRX effect to handle the HTTP request when a Book is added and to dispatch a new Success action.

addBook$ = createEffect(() =>
this.actions.pipe(
ofType(BookActions.BookActionType.Add_Book), // Listen for the 'Add_Book' action
mergeMap((action) => {
return this.api.fakeApiCall().pipe(
map((result) => {
return new BookActions.SuccessAction(result);
})
);
})
)
);

And the success action is defined as follows:

export class SuccessAction implements Action {
readonly type = BookActionType.Success;
//add an optional payload
constructor(public payload: BookItem) {
}
}

Service Layer: Ensure that you have a service layer (e.g., ApiService) that encapsulates the HTTP requests and communicates with your backend API.

export class ApiService {
constructor() {}
fakeApiCall(): Observable<BookItem> {
return interval(1000).pipe(
take(1),
map(() => {
return {
id: 2,
author: 'William Shakespeare',
name: 'Henry VI',
type: 'classical',
};
}));
}
}

Import the effect into app module:

imports: [
EffectsModule.forRoot([BookEffects]),
]

Update the reducer to handle the Success action that is dispatched when the HTTP request is successful. This action should update the application state with the new data.

export function BookReducer(
state: Array<BookItem> = initialState,
action: Action
) {
switch (action.type) {
case BookActionType.Success:
const addBookAction = action as SuccessAction;
return [...state, addBookAction.payload];
default:
return state;
}
}

Update the book action to ensure that the success action is triggered when the API response is successful.

This design keeps your application architecture clean and maintainable. Reducers handle state changes, effects manage side effects, and services handle API interactions. This approach aligns with the principles of the NGRX library, making your code easier to test and scale.

The updated repo can be found at this link.

The Redux tool shows two actions triggered upon submitting a new book entry via the form. The first action is Add_Book, which is fired instantly upon submitting the form data. The second action occurs upon successful API request. In this project we are simulating the API result by delaying the firing of the success action via interval(1000) in api.service.ts file.

5. Insights on building a scalable datastore

So far, we have successfully developed a basic datastore that interacts with both user state and backend data. As you may have noticed, our codebase includes various functions such as store.select, store.dispatch, and createEffect. This implies that any developer aiming to develop new features involving API data retrieval must first become familarize themselves with the datastore concept and then replicate similar implementations. This requirement can be daunting for newcomers, who may find it challenging to quickly grasp all the new tools and paradigms. Additionally, allowing beginners to use complex tools without a deep understanding of them can be very risky. To mitigate these issues, we can construct a custom wrapper around the NGRX datastore features, offering a simplified interface for developers. This approach not only eases the learning curve but also simplifies future upgrades. Imagine the convenience of not having to search through the entire codebase to replace every instance of store.select, store.dispatch, and createEffect with their updated versions!

As the application grows, automated testing becomes increasingly important (and not optional!) Datastore architecture facilitates UI testing through its inherent feature of switching data sources. For example, it’s quite straightforward to shift from real backend data fetched via HTTP requests to using mocked data fed directly into the datastore.

This capability allows the application to operate even without having an actual backend structure in place. This means that we can further utilize datastore to quicky design a prototype or a product demo. This blog post aims to equip you with an understanding of how the NGRX datastore functions, both in theory and in practice. In the next post, I will cover building a custom wrapper for the NGRX datastore and demonstrate how to utilize it in UI testing.

Thank you for reading. I hope you found the content useful. 🐻

--

--

Sophia Zhang
Sophia Zhang

Written by Sophia Zhang

SophiaZhang.com Welcome to my world, let’s explore the golden rules for building a reliable,scalable, reliable and maintainable web application.

No responses yet