What is NgRx?
NgRx is RxJS powered, inspired by Redux state management lib for Angular2.
Basic Philosophy
Like many state management frameworks like Redux - app skeleton must include following module types - Store, Actions and Reducers
Store
simple class or object representing the application state
import postListReducer, * as fromPostList from './post-list';
import postReducer, * as fromPost from './post';
export interface AppState {
posts: fromPostList.PostListState;
post: fromPost.PostState;
};
Actions
function that passes type and params of what reducer should do
static LOAD_POSTS = '[Post] Load Posts';
loadPosts(): Action {
return {
type: PostActions.LOAD_POSTS
};
}
Reducers
Immutable function that returns new object containing changed current state returned
export default function (state = initialState, action: Action): PostListState {
switch (action.type) {
case PostActions.LOAD_POST_SUCCESS: {
return action.payload;
}
}
}
Effects
Since state actions are asynchronous - it is better to take advantage of using effects:
@Effect() loadPosts$ = this.update$
.ofType(PostActions.LOAD_POSTS)
.switchMap(() => {
return this.svc.getAllSections();
})
.map(posts => this.postActions.loadPostsSuccess(posts));
Refactoring our components
Now we can replace our logic inside components:
Instead of:
this.loadHtml.getPost(params['id']).subscribe(post => {
this.post = post;
})
We can now write:
this.store.dispatch(this.postActions.getPOST(this.name));
...
...
store.select('post').subscribe((post:Post) => {
this.post = post;
})
Much more accurate, is it?
No comments:
Post a Comment