【发布时间】:2017-06-13 10:07:06
【问题描述】:
所以我已经多次阅读this 的帖子,但现在定义的设置和示例与store example app 中显示的方法不同。
我已经编写了我的商店代码,很大程度上基于示例应用程序,所以如果我们继续使用示例应用程序作为本文中的参考:
图书缩减器:
export interface State {
ids: string[];
entities: { [id: string]: Book };
selectedBookId: string | null;
};
const initialState: State = {
ids: [],
entities: {},
selectedBookId: null,
};
export function reducer(state = initialState, action: book.Actions | collection.Actions): State {
switch (action.type) {
case book.ActionTypes.SEARCH_COMPLETE:
case collection.ActionTypes.LOAD_SUCCESS: {
const books = action.payload;
const newBooks = books.filter(book => !state.entities[book.id]);
const newBookIds = newBooks.map(book => book.id);
const newBookEntities = newBooks.reduce((entities: { [id: string]: Book }, book: Book) => {
return Object.assign(entities, {
[book.id]: book
});
}, {});
return {
ids: [ ...state.ids, ...newBookIds ],
entities: Object.assign({}, state.entities, newBookEntities),
selectedBookId: state.selectedBookId
};
}
export const getEntities = (state: State) => state.entities;
export const getIds = (state: State) => state.ids;
reducers index.ts(缩短但保留相关信息):
import { createSelector } from 'reselect';
import { compose } from '@ngrx/core/compose';
import { storeFreeze } from 'ngrx-store-freeze';
import { combineReducers } from '@ngrx/store';
import * as fromBooks from './books';
export interface State {
books: fromBooks.State;
}
const reducers = {
books: fromBooks.reducer,
};
const productionReducer: ActionReducer<State> = combineReducers(reducers);
export function reducer(state: any, action: any) {
return productionReducer(state, action);
}
export const getBooksState = (state: State) => state.books;
export const getBookEntities = createSelector(getBooksState, fromBooks.getEntities);
export const getBookIds = createSelector(getBooksState, fromBooks.getIds);
现在我不太明白“查询”是如何构建的,我想要做的就是将一个 ID 说“456”传递给一个函数,该函数将使用 id 从书中查看 State 456"。将此数据返回到 Book 的 observable 中,以便我可以在模板/组件中使用它。
我已经看了几个小时的示例代码,当我认为我已经掌握了它时,我无法弄清楚我做错了什么。如果有人能够解释如何构建一个接受自定义参数的选择器。
我使用了示例应用程序中的确切代码,希望如果找到答案,它将对未来的读者有所帮助。
【问题讨论】: