I'm a beginner with ngrx/store and this is my first project using it.
I have successfully set up my angular project with ngrx/store and I'm able to dispatch a load action after initializing my main component like this:
ngOnInit() { this.store.dispatch({type: LOAD_STATISTICS}); }
I have set up an effect to load the data when this action is dispatched:
@Effect()
loadStatistic = this.actions.ofType(LOAD_STATISTICS).switchMap(() => {
return this.myService.loadStatistics().map(response => {
return {type: NEW_STATISTICS, payload: response};
});
});
My reducer looks like this:
reduce(oldstate: Statistics = initialStatistics, action: Action): Statistic {
switch (action.type) {
case LOAD_STATISTICS:
return oldstate;
case NEW_STATISTICS:
const newstate = new Statistics(action.payload);
return newstate;
....
Although this works, I can't get my head around how to use this with a router guard as I currently need to dispatch the LOAD_ACTION only once.
Also, that a component has to dispatch a LOAD action, to load initial data doesn't sound right to me. I'd expect that the store itself knows that it needs to load data and I don't have to dispatch an action first. If this were the case, I could delete the ngOnInit() method in my component.
I already have looked into the ngrx-example-app but I haven't understood really how this works.
EDIT:
After adding a resolve guard that returns the ngrx-store observable the route does not get activated. Here is the resolve:
@Injectable()
export class StatisticsResolver implements Resolve<Statistic> {
resolve(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): Observable<Statistic> {
// return Observable.of(new Statistic());
return this.store.select("statistic").map(statistic => {
console.log("stats", statistic);
return statistic;
});
}
This is the route:
const routes: Routes = [
{path: '', component: TelefonanlageComponent, resolve: {statistic: TelefonieStatisticResolver}},
];