@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.
-
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() ] };
3.1. Use NgrxRouterStateModule
:
```typescript
import { ApplicationConfig } from '@angular/core';
import { NgrxRouterStateModule } from '@ngrxs/router-store';
@NgModule({
imports: [NgrxRouterStateModule.forRoot()]
})
export class MyModule {
}
```
- Done! You can see
ngrx-router
state inRedux DevTools
.
@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);
}
Selectors | Usage |
---|---|
selectCurrentUrl | Select current route url |
selectRouterActiveRoutes | Select current activated routes |
selectRouterParams | Select route parameters |
@ngrxs/router-store
exposes interfaces used by serialized state.
NgrxRouterState
{
url: string;
routes: string[];
params: Params;
}
You can also do navigation events with @ngrxs/router-store
.
import { goToUrl } from '@ngrxs/router-store';
this.store.dispatch(goToUrl({ url: '/books' }));
@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())
)
);