First, you should take a look into @ngrx/store
documentation : https://github.com/ngrx/store#setup
I've made a small (funny) project to demonstrate how to use :
- angular
- ngrx/store
- ngrx/effects
- normalized state
- selectors
You can find it here : https://github.com/maxime1992/pizza-sync
To give you some info about how it works :
-
core.module.ts is were I declare my root reducer
-
root.reducer.ts is were I build the root reducer and
compose it with middlewares according to dev/prod env
- For a reducer, I keep every
related part together (interface(s) + reducer + effects + selectors)
Then within a component, to access the store simply do like that :
Inject the store :
constructor(private _store$: Store<IStore>) { }
Get data from either
a) A selector (ex)
this._pizzasCategories$ = this._store$.let(getCategoriesAndPizzas());
b) Directly from the store (ex)
this._idCurrentUser$ = this
._store$
.select(state => state.users.idCurrentUser);
Notice that I didn't subscribe
which means I'm using in my view the async
pipe so angular subscribe to the Observable for me.
But of course you can also do it by hand and use subscribe in your ts.
PS: I'll be releasing a starter with all that already setup to avoid loosing time with all of that when starting a new project. I'll try to release it this week and I'll update this post as soon as it's done. Maybe it might help you.
EDIT 12/05/17
Late but I finally released the starter :) !
https://github.com/maxime1992/angular-ngrx-starter
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…