Currently, I am developing an angular2 application that implements the ngrx store approach for state management. The source code for the app is available on github here
The Issue at Hand
The specific challenge I am encountering with this method involves handling values emitted from one observable in cases where another observable returns null.
I prefer not to query the backend API if the required data is already present in my ngrx store.
Angular2 Code
Here is an excerpt from my trips.reducer.ts
file
export interface State {
ids: string[];
trips: { [id: string]: Trip };
selectedTripId: string;
}
const initialState = {
ids: [],
trips: {},
selectedTripId: null
}
export function reducer(state = initialState, action: Action ): State {}
export function getTrips(state : State) {
return state.trips;
}
export function getTripIds(state: State) {
return state.ids;
}
export function getSelectedTripId(state: State) {
return state.selectedTripId;
}
And here is a snippet from my base reducer index.ts
export interface State {
trips: fromTripsReducer.State;
}
const reducers = {
trips: fromTripsReducer.reducer,
}
//Other selector functions and mappings...
Now, within my trip-detail.component.ts
, I can access a particular trip like this
selectedTrip$: Trip;
constructor(private store: Store<fromRoot.State>) {
this.selectedTrip$ = this.store.select(fromRoot.getSelectedTrip);
}
However, upon reloading the route as localhost:4200/trips/2
, the store will reset to its initialState which could lead to issues when the expected data is missing.
In such scenarios, it may be necessary to resort to backend requests only if the required trip information is not available in the store and
the selectedTrip$
object returns null or undefined.
this.selectedTrip$ = this.store.select(fromRoot.getSelectedTrip);