从使用 NgRx 选择商店获取对象而不是列表
Posted
技术标签:
【中文标题】从使用 NgRx 选择商店获取对象而不是列表【英文标题】:Getting object instead of list from selecting the store with NgRx 【发布时间】:2021-05-28 08:09:02 【问题描述】:我在从商店的状态中检索列表时遇到问题,因为该列表是用一个对象包裹的。
这是我的代码
beer-list.component.ts
@Component(
selector: 'app-beer-list',
templateUrl: './beer-list.component.html',
styleUrls: ['./beer-list.component.css']
)
export class BeerListComponent implements OnInit
public beers$: Observable<Beer[]>;
constructor(private store: Store<BeerState>)
ngOnInit(): void
this.beers$ = this.store.select((state: BeerState) => state.beers);
this.store.dispatch(getBeersOnTap());
beer.actions.ts
export const getBeersOnTap = createAction(
'[Beer List] Get beers'
);
export const getBeersOnTapSuccess = createAction(
'[Beer List] Get beers succeeded',
props<beers: Beer[]>()
);
export const getBeersOnTapFailed = createAction(
'[Beer List] Get beers failed'
);
beer.reducers.ts
export interface BeerState
beers: Beer[];
export const initialState: BeerState =
beers: []
;
export const beerReducer = createReducer(
initialState,
on(getBeersOnTapSuccess, (state, beers) => (...state, beers: beers) // Payload comes from an effect
));
export function reducer(state: BeerState | undefined, action: Action)
return beerReducer(state, action);
我从商店里挑选啤酒得到了什么:
beers:
beers: [
...
【问题讨论】:
【参考方案1】:beerReducer
可能已添加到beers
功能中?所以你必须先选择啤酒状态。
this.beers$ = this.store.select((state: AppState) => state.beers.beers);
【讨论】:
感谢您的回答!找到了一个接近你提议的解决方法。但是我想从商店中选择:((state: BeerState) => state.beers
。 StoreModule
在 app.module.ts 中定义为:StoreModule.forRoot(beers: beerReducer)
【参考方案2】:
好的。我终于弄明白了。我需要调整状态树并添加一些选择器来选择商店中的啤酒。
这是我更新的 NgRx 代码,其中更改了注释:
beer-list.component.ts
@Component(
selector: 'app-beer-list',
templateUrl: './beer-list.component.html',
styleUrls: ['./beer-list.component.css']
)
export class BeerListComponent implements OnInit
public beers$: Observable<Beer[]>;
constructor(private store: Store<AppState>)
ngOnInit(): void
this.beers$ = this.store.select(selectBeers); // Using selector here
this.store.dispatch(getBeersOnTap());
app.state.ts(新文件)
export interface AppState
beerState: BeerState
beer.selectors.ts(新文件)
const selectBeerState = (state: AppState) => state.beerState;
export const selectBeers = createSelector(
selectBeerState,
(state) => state.beers
)
【讨论】:
以上是关于从使用 NgRx 选择商店获取对象而不是列表的主要内容,如果未能解决你的问题,请参考以下文章