18.0.2 • Published 1 year ago
@ngrxs/router-store v18.0.2
@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/routerand@ngrx/store.npm install --save @ngrxs/router-storeImport
provideNgrxRouterStateinapp.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-routerstate 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())
)
);