1.1.0 • Published 3 months ago
@ngrxs/router-store v1.1.0
@ngrxs/router-store
@ngrxs/router-store
library serializes Angular router snapshots for NgRx Router Store. It searches entire route tree and puts only useful attributes into NgRx store.
Installation
Make sure that you've installed and setup
@angular/router
and@ngrx/store
.npm install --save @ngrxs/router-store
Import
provideNgrxRouterState
inapp.config.ts
:import { ApplicationConfig } from '@angular/core'; import { provideNgrxRouterState } from '@ngrxs/router-store'; export const appConfig: ApplicationConfig = { providers: [ provideNgrxRouterState() ] };
Done! You can see
ngrx-router
state inRedux DevTools
.
Advanced Use
Usage
@ngrxs/router-store
provides selectors which you can use to select route properties.
import { Component } from '@angular/core';
import { Store } from '@ngrx/store';
import { selectCurrentUrl } from '@ngrxs/router-store';
@Component({
template: 'url: {url$ | async}',
styles: []
})
export class RouteComponent {
#store = inject(Store);
url$ = this.#store.select(selectCurrentUrl);
}
List of Selectors
Selectors | Usage |
---|---|
selectCurrentUrl | Select current route url |
selectRouterActiveRoutes | Select current activated routes |
selectRouterParams | Select route parameters |
Interfaces
@ngrxs/router-store
exposes interfaces used by serialized state.
NgrxRouterState
{
url: string;
routes: string[];
params: Params;
}
Actions
You can also do navigation events with @ngrxs/router-store
.
import { goToUrl } from '@ngrxs/router-store';
this.store.dispatch(goToUrl({ url: '/books' }));
RxJs operators
@ngrxs/router-store
provides operators you can use to filter by routes
import { ofRoute, onLeaveRoute } from '@ngrxs/router-store';
onPageEnter$ = createEffect(() =>
this.#actions$.pipe(
ofRoute(['/books']),
map(() => loadBooks())
)
);
onPageLeave$ = createEffect(() =>
this.#actions$.pipe(
onLeaveRoute(['/books']),
map(() => clearBooks())
)
);