The user wants to build an Angular application that uses two specific features:
- NgRx: For state management (specifically "advanced" state management, implying actions, reducers, effects, selectors).
- Lazy Loading: For optimizing load times by loading feature modules on demand.
The prompt is a bit broad ("Build an Angular application..."). Since I am an AI text model, I cannot literally build and host the application. I need to provide the code structure and implementation details to guide the user in building it.
Key Steps to Cover:
- Prerequisites/Setup: Creating a new project, installing dependencies.
- Project Structure: How to organize files for scalability (Core, Shared, Features).
- Lazy Loading Setup: Defining the
AppRoutingModule and a feature module routing.
- NgRx Implementation:
- State Interface: Define the shape of the data.
- Actions: Define events.
- Reducers: Define state transitions.
- Selectors: Query the state.
- Effects: Handle side effects (like API calls).
- Facade (Optional but good for "advanced"): A pattern to simplify component interaction with the store.
- Feature Module Integration: Connecting the lazy-loaded module to the store using
StoreModule.forFeature.
- Component Usage: How to dispatch actions and select data in a component.
Scenario Selection:
To make the example concrete, I'll use a classic "Products" or "Todo" feature. A "Products" feature is better because it usually involves an HTTP request (Effect), which fits the "advanced" requirement better than a simple synchronous toggle.
Drafting the Content - Section by Section:
-
Step 1: Scaffolding
ng new ngrx-lazy-app
npm install @ngrx/store @ngrx/effects @ngrx/store-devtools
-
Step 2: The Feature Module (Lazy Loaded)
- Create a module
ProductsModule.
- Set up routing in
AppModule to lazy load ProductsModule.
-
Step 3: NgRx State Management (The Core Request)
- State:
Product interface, ProductState.
- Actions:
loadProducts, loadProductsSuccess, loadProductsFailure.
- Reducer: Handle the transitions (loading flag, data array).
- Selectors:
selectAllProducts, selectLoading.
- Effects: Inject
Actions and ProductService. SwitchMap to handle the API call.
-
Step 4: Registering the Store
- Crucial point: In the Feature module, use
StoreModule.forFeature('products', reducer).
- In the App module (or Core module), import
StoreModule.forRoot({}) and EffectsModule.forRoot([]).
-
Step 5: The Component
- Inject
Store.
ngOnInit: Dispatch loadProducts.
- Async pipe usage (best practice).
-
Refinement for "Advanced" State Management:
- Using
createFeatureSelector and createSelector.
- Using
StoreDevtools configuration.
- Briefly mentioning folder structure (Grouping by feature vs. Grouping by type). I'll stick to grouping by feature inside the module for better lazy loading context.
Self-Correction/Review during drafting:
- Initial thought: Should I include a real backend?
- Correction: No, keep it self-contained. Mock the service or just show the service signature to save space and focus on NgRx.
- Check: Did I mention
CommonModule vs BrowserModule? Yes, BrowserModule in App, CommonModule in Feature.
Final Output Structure:
- Project Setup Commands.
- Directory Structure visualization.
- Implementation of the Feature (State, Actions, Reducer, Selectors, Effects).
- Feature Module Configuration (connecting the store).
- App Module Configuration (Root store & Lazy Loading routes).
- Component implementation.
Let's write the code.
Code specifics:
- Angular CLI commands.
products.actions.ts
products.reducer.ts
products.selectors.ts
products.effects.ts
products.module.ts
app-routing.module.ts
This looks solid. I will present it as a step-by-step tutorial.
One specific detail for "Advanced" state management: Using @ngrx/entity is often considered advanced, but it adds significant boilerplate code that might confuse a tutorial. I will stick to standard store but mention that entity is good for collections. I will focus on the Side Effects pattern as the "advanced" part.
Let's go.
This guide will walk you through building a scalable Angular application structure featuring NgRx (for state management) and Lazy Loading (for performance).
We will build a "Product Dashboard" feature that is lazy-loaded and manages its state via NgRx.
Prerequisites
Ensure you have the Angular CLI installed:
npm install -g @angular/cli
Step 1: Project Setup
Create a new workspace and install the necessary NgRx libraries.
ng new ngrx-lazy-app
# Select CSS or SCSS when asked
# Select "Yes" for Server-Side Rendering (SSR) if desired (optional for this demo)
cd ngrx-lazy-app
npm install @ngrx/store @ngrx/effects @ngrx/store-devtools @ngrx/entity
Step 2: Define the Feature State (Domain Logic)
We will create a "Product" feature. Even though this will be lazy-loaded, we define the State Interface and Selectors in a way that allows them to be accessed globally if needed, or strictly within the feature.
Create the folder structure:
src/app/products/store/
1. The State Interface (product.state.ts)
import { Product } from '../models/product.model';
export interface ProductState {
products: Product[];
loading: boolean;
error: string | null;
}
export const initialProductState: ProductState = {
products: [],
loading: false,
error: null
};
2. Actions (product.actions.ts)
import { createAction, props } from '@ngrx/store';
import { Product } from '../models/product.model';
export const loadProducts = createAction('[Product List] Load Products');
export const loadProductsSuccess = createAction('[Product API] Load Success', props<{ products: Product[] }>());
export const loadProductsFailure = createAction('[Product API] Load Failure', props<{ error: string }>());
3. Reducer (product.reducer.ts)
import { createReducer, on } from '@ngrx/store';
import { ProductState, initialProductState } from './product.state';
import * as ProductActions from './product.actions';
export const productReducer = createReducer(
initialProductState,
// Trigger loading
on(ProductActions.loadProducts, (state) => ({
...state,
loading: true,
error: null
})),
// Handle Success
on(ProductActions.loadProductsSuccess, (state, { products }) => ({
...state,
products,
loading: false
})),
// Handle Failure
on(ProductActions.loadProductsFailure, (state, { error }) => ({
...state,
loading: false,
error
}))
);
4. Selectors (product.selectors.ts)
import { createFeatureSelector, createSelector } from '@ngrx/store';
import { ProductState } from './product.state';
// 1. Select the feature slice from the global state
export const selectProductState = createFeatureSelector<ProductState>('products');
// 2. Select specific pieces of state
export const selectAllProducts = createSelector(
selectProductState,
(state) => state.products
);
export const selectProductLoading = createSelector(
selectProductState,
(state) => state.loading
);
Step 3: Side Effects (Advanced State Management)
Effects handle asynchronous operations (like API calls) keeping your reducers pure.
Effects (product.effects.ts)
import { Injectable } from '@angular/core';
import { Actions, createEffect, ofType } from '@ngrx/effects';
import { ProductService } from '../services/product.service';
import * as ProductActions from './product.actions';
import { catchError, map, mergeMap } from 'rxjs/operators';
import { of } from 'rxjs';
@Injectable()
export class ProductEffects {
constructor(
private actions$: Actions,
private productService: ProductService
) {}
loadProducts$ = createEffect(() =>
this.actions$.pipe(
ofType(ProductActions.loadProducts),
mergeMap(() =>
this.productService.getProducts().pipe(
map((products) => ProductActions.loadProductsSuccess({ products })),
catchError((error) => of(ProductActions.loadProductsFailure({ error: error.message })))
)
)
)
);
}
(Note: You would need a simple ProductService injecting HttpClient to make this work, mocked or real).
Step 4: The Lazy Loaded Module
This is where the magic happens. We register the store locally within the feature module.
products.module.ts
import { NgModule } from '@angular/core';
import { CommonModule } from '@angular/common';
import { RouterModule, Routes } from '@angular/router';
import { StoreModule } from '@ngrx/store';
import { EffectsModule } from '@ngrx/effects';
import { ProductListComponent } from './components/product-list.component';
import { productReducer } from './store/product.reducer';
import { ProductEffects } from './store/product.effects';
const routes: Routes = [
{ path: '', component: ProductListComponent }
];
@NgModule({
declarations: [ProductListComponent],
imports: [
CommonModule,
RouterModule.forChild(routes),
// ADVANCED FEATURE: Registering state lazily
// The key 'products' will be added to the global store
// ONLY when this module is loaded.
StoreModule.forFeature('products', productReducer),
EffectsModule.forFeature([ProductEffects])
],
providers: [ProductService] // Assume this service exists
})
export class ProductsModule {}
The Component (product-list.component.ts)
import { Component, OnInit } from '@angular/core';
import { Store } from '@ngrx/store';
import { Observable } from 'rxjs';
import { Product } from '../models/product.model';
import * as ProductActions from '../store/product.actions';
import * as ProductSelectors from '../store/product.selectors';
@Component({
selector: 'app-product-list',
template: `
<div *ngIf="loading$ | async">Loading...</div>
<ul>
<li *ngFor="let product of products$ | async">
{{ product.name }} - ${{ product.price }}
</li>
</ul>
`
})
export class ProductListComponent implements OnInit {
products$: Observable<Product[]>;
loading$: Observable<boolean>;
constructor(private store: Store) {
// Using selectors to stream data
this.products$ = this.store.select(ProductSelectors.selectAllProducts);
this.loading$ = this.store.select(ProductSelectors.selectProductLoading);
}
ngOnInit() {
// Dispatch action to trigger the Effect
this.store.dispatch(ProductActions.loadProducts());
}
}
Step 5: Global Configuration (App Module)
In the main application, we set up the root store and define the routing to lazy load the module we just created.
app-routing.module.ts
import { NgModule } from '@angular/core';
import { RouterModule, Routes } from '@angular/router';
const routes: Routes = [
{
path: 'products',
loadChildren: () => import('./products/products.module').then(m => m.ProductsModule)
},
{ path: '', redirectTo: '/products', pathMatch: 'full' }
];
@NgModule({
imports: [RouterModule.forRoot(routes)],
exports: [RouterModule]
})
export class AppRoutingModule {}
app.module.ts
import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { StoreModule } from '@ngrx/store';
import { EffectsModule } from '@ngrx/effects';
import { StoreDevtoolsModule } from '@ngrx/store-devtools';
import { AppComponent } from './app.component';
import { AppRoutingModule } from './app-routing.module';
@NgModule({
declarations: [AppComponent],
imports: [
BrowserModule,
AppRoutingModule,
// Initialize the Root Store
StoreModule.forRoot({}, {}),
// Initialize Root Effects (can be empty if all effects are in lazy modules)
EffectsModule.forRoot([]),
// Dev Tools configuration
StoreDevtoolsModule.instrument({ maxAge: 25 })
],
bootstrap: [AppComponent]
})
export class AppModule {}
Summary of Concepts Used
-
Lazy Loading:
- The
AppRoutingModule uses loadChildren to fetch the ProductsModule only when the user visits /products.
- This reduces the initial bundle size significantly.
-
Advanced State Management (NgRx):
- Actions: Describe events.
- Reducers: Synchronous state changes.
- Effects: Handling side effects (API calls) isolating business logic from UI.
- Selectors: Efficient, composable queries of the store state.
-
Lazy State Registration:
- By using
StoreModule.forFeature('products', reducer) inside the lazy-loaded module, the "products" slice of state does not exist in the global store until the user navigates to that feature. This keeps the initial state tree minimal.