npm install @ngrx/router-store --save
- Use the
routerReducer
when providing theStoreModule.provideStore
and add theRouterStoreModule.connectRouter
to the@NgModule.imports
:
import { StoreModule } from '@ngrx/store';
import { routerReducer, RouterStoreModule } from '@ngrx/router-store';
@NgModule({
imports: [
BrowserModule,
StoreModule.provideStore({ router: routerReducer }),
RouterStoreModule.connectRouter()
],
bootstrap: [ AppComponent ]
})
export class AppModule {
}
- Add
RouterState
to main application state:
import { RouterState } from '@ngrx/router-store';
export interface AppState {
router: RouterState;
// [other state members here]
};
- Combine reducer with other reducers:
const reducers = {
router: routerReducer,
// [other reducers here]
};
- (Optional) Set the initial value for the router state by providing it in @NgModule:
StoreModule.provideStore({ router: routerReducer }, {
router: {
path: window.location.pathname + window.location.search
}
})
or directly in initial state variable:
const initialState: AppState = {
router: {
path: window.location.pathname + window.location.search,
},
// [other initializers here]
import { go, replace, search, show, back, forward } from '@ngrx/router-store';
store.dispatch(go(['/path', { routeParam: 1 }], { query: 'string' }));
store.dispatch(replace(['/path'], { query: 'string' }));
store.dispatch(show(['/path'], { query: 'string' }));
store.dispatch(search({ query: 'string' }));
store.dispatch(back());
store.dispatch(forward());
The Angular Router Navigation Extras are supported with each router action.
import { NavigationExtras } from '@angular/router';
let extras: NavigationExtras = {
relativeTo: ActivatedRoute,
fragment: string,
preserveQueryParams: boolean,
preserveFragment: boolean,
skipLocationChange: boolean,
replaceUrl: boolean
};
store.dispatch(go(['path', { routeParam: 1 }], { query: 'string' }, extras));