Reputation: 10932
I'm trying to get a grip on Redux state management in my Angular 2 app and am wondering how Redux state and Angular 2 routing can play nicely together.
For example, I have various views (i.e. components with separate routes) that take a date or a date range. So in my app bar I got a button that will display a calendar for the user to pick a date. The view then gets this date as a query parameter,
http://localhost:3000/view&date=20160928
I can then retrieve the date inside the component by listening to the activated route query parameters
this.route.queryParams.subscribe(params => <load records for date>);
Now how would I do this with Redux, that is, how am I supposed to keep the state in the Redux store only? At first I thought I'd just get the date parameter and dispatch it as DATE_ACTION_CHANGE
to the store and then in turn would listen to the state change
date$ = this.ngRedux.select(state => state.date)
.subscribe(date => <load records for date>);
Is that the recommended way of doing this? It works OK as long as I have just one observable. However, I get parameters from various sources. For example, another parameter would be a client's ID. That in turn is part of the URL,
localhost:3000//client/45&date=20160928
That is when it gets hazy, should I update the store with ID and date and then listen for both properties in the state to change? What if one changes, but the other does not? I have a feeling I'm doing this wrong, any pointers?
Upvotes: 6
Views: 3530
Reputation: 115
What you should probably consider is the following library:
https://github.com/ngrx/router-store (in case you are using ngrx/store).
It provides bindings to connect angular/router to ngrx/store. It also provdes the following store dispatch actions:
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());
You can also check this one: https://github.com/dagstuan/ng2-redux-router
Upvotes: 6