ngrx/store:保存了ReduxAPI的核心概念,使用RxJS扩展的Redux实现。使用可观察对象来简化了监听事件的订阅等操作。
dispatcher,reducer,state都是基于BehaviorSubject的 BehaviorSubject:储存着要发射给消费者的最新的值。无论何时一个新的观察者订阅它,都会立即接受到这个来自BehaviorSubject的”当前值”。
创建一个应用存储的接口可以便于理解reducers是如何用于应用的。如果需要额外的功能,存储可以扩展新的键值对来容纳更新的模型。
store的select方法:定义当state改变时,state的哪一部分应该被返回,返回一个Observable对象。
一个小例子:
// The "items" reducer performs actions on our list of items export const items = (state: any = [], {type, payload}) => { switch (type) { default: return state; } }; // The "selectedItem" reducer handles the currently selected item export const selectedItem = (state: any = null, {type, payload}) => { switch (type) { default: return state; } }; export interface AppStore { items: Item[]; selectedItem: Item; } this.videos$ = this.store.select(state => state.videos);安装相应npm包
npm install ngrx/store ngrx/core --save-dev
定义store模块
创建action与reducer连接reducer与store模块在组件或服务中使用reducer