Skip to content

Bindings to connect the Angular Router to @ngrx/store

License

Notifications You must be signed in to change notification settings

moniuch/router-store

 
 

Repository files navigation

@ngrx/router-store

Bindings to connect angular/router to ngrx/store

Installation

npm install @ngrx/router-store --save

Setup

  1. Use the routerReducer when providing the StoreModule.provideStore and add the RouterStoreModule.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 {
}
  1. Add RouterState to main application state:
import { RouterState } from '@ngrx/router-store';

export interface AppState {
  router: RouterState;
  // [other state members here]
};
  1. Combine reducer with other reducers:
const reducers = {
  router: routerReducer,
  // [other reducers here]
};
  1. (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]

Dispatching Actions

import { go, replace, search, show, back, forward } from '@ngrx/router-store';

Navigation with a new state into history

store.dispatch(go(['/path', { routeParam: 1 }], { query: 'string' }));

Navigation with replacing the current state in history

store.dispatch(replace(['/path'], { query: 'string' }));

Navigation without pushing a new state into history

store.dispatch(show(['/path'], { query: 'string' }));

Navigation with only changing query parameters

store.dispatch(search({ query: 'string' }));

Navigating back

store.dispatch(back());

Navigating forward

store.dispatch(forward());

Navigation Extras

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));

About

Bindings to connect the Angular Router to @ngrx/store

Resources

License

Stars

Watchers

Forks

Packages

No packages published

Languages

  • TypeScript 87.5%
  • JavaScript 12.5%