Skip to content

Instantly share code, notes, and snippets.

@CodeByKwakes
Last active March 16, 2023 12:09
Show Gist options
  • Save CodeByKwakes/82a8e567107cab352b4d30b1cb202749 to your computer and use it in GitHub Desktop.
Save CodeByKwakes/82a8e567107cab352b4d30b1cb202749 to your computer and use it in GitHub Desktop.
NgRx Guide #ngrx

NGRX Guide

Introduction

ngrx is a reactive library for Angular that enables state management of your application. It implements the Redux pattern inspired by the React community, providing an observable store that can be subscribed to and dispatch actions that trigger updates to the store.

Installation

To install ngrx, run the following command:

# Required Packages
npm install --save @ngrx/{store,effects,entity,router-store,component-store}

# Optional Packages
npm install --save-dev @ngrx/{store-devtools,schematics}
import { Params, RouterStateSnapshot } from '@angular/router';
import { RouterStateSerializer } from '@ngrx/router-store';
export interface RouterStateUrl {
url: string;
params: Params;
queryParams: Params;
}
export class CustomSerializer implements RouterStateSerializer<RouterStateUrl> {
serialize(routerState: RouterStateSnapshot): RouterStateUrl {
let route = routerState.root;
while (route.firstChild) {
route = route.firstChild;
}
const {
url,
root: { queryParams }
} = routerState;
const { params } = route;
// Only return an object including the URL, params and query params
// instead of the entire snapshot
return { url, params, queryParams };
}
}
import { createActionGroup, emptyProps, props } from '@ngrx/store';
import { NavigationExtras } from '@angular/router';
export const RouterActions = createActionGroup({
source: 'Router',
events: {
Go: props<{
path: any[];
query?: object;
extras?: NavigationExtras;
}>(),
Back: emptyProps(),
Forward: emptyProps()
}
});
import { createAction, emptyProps, props } from '@ngrx/store';
import { NavigationExtras } from '@angular/router';
export const go = createAction(
'[Router] Go',
props<{
path: any[];
query?: object;
extras?: NavigationExtras;
}>()
);
export const back = createAction('[Router] Back');
export const forward = createAction('[Router] Forward');
import { Location } from '@angular/common';
import { Injectable } from '@angular/core';
import { Router } from '@angular/router';
import { Actions, createEffect, ofType } from '@ngrx/effects';
import * as routerActions from './router.actions';
import { tap } from 'rxjs/operators';
@Injectable()
export class RouterEffects {
navigate$ = createEffect(
() =>
this.actions$.pipe(
ofType(routerActions.go),
tap(({ path, query: queryParams, extras }) => {
this.router.navigate(path, { queryParams, ...extras });
})
),
{ dispatch: false }
);
navigateBack$ = createEffect(
() =>
this.actions$.pipe(
ofType(routerActions.back),
tap(() => this.location.back())
),
{ dispatch: false }
);
navigateForward$ = createEffect(
() =>
this.actions$.pipe(
ofType(routerActions.forward),
tap(() => this.location.forward())
),
{ dispatch: false }
);
constructor(
private actions$: Actions,
private router: Router,
private location: Location
) {}
}
import { getRouterSelectors } from '@ngrx/router-store';
// `router` is used as the default feature name. You can use the feature name
// of your choice by creating a feature selector and pass it to the `getRouterSelectors` function
// export const selectRouter = createFeatureSelector<RouterReducerState>('yourFeatureName');
export const {
selectCurrentRoute, // select the current route
selectFragment, // select the current route fragment
selectQueryParams, // select the current route query params
selectQueryParam, // factory function to select a query param
selectRouteParams, // select the current route params
selectRouteParam, // factory function to select a route param
selectRouteData, // select the current route data
selectRouteDataParam, // factory function to select a route data param
selectUrl, // select the current url
selectTitle // select the title if available
} = getRouterSelectors();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment