要在Angular应用中使用NGRX实体进行过滤,可以按照以下步骤操作:
npm install @ngrx/store @ngrx/entity
feature
的新的NGRX特性模块。在该模块中,定义实体的状态、操作和选择器。可以使用以下命令创建该模块:ng generate module feature
feature
模块中,创建一个名为entity.reducer.ts
的新的NGRX实体reducer文件。在该文件中,定义实体的初始状态和reducer函数。以下是一个示例代码:import { createReducer, on } from '@ngrx/store';
import { EntityState, EntityAdapter, createEntityAdapter } from '@ngrx/entity';
import { MyEntity } from './my-entity.model';
import * as MyEntityActions from './my-entity.actions';
export interface State extends EntityState {
// 定义其他状态属性
filter: string;
}
export const adapter: EntityAdapter = createEntityAdapter();
export const initialState: State = adapter.getInitialState({
// 初始化其他状态属性
filter: ''
});
export const reducer = createReducer(
initialState,
on(MyEntityActions.setFilter, (state, { filter }) => ({ ...state, filter })),
// 定义其他reducer操作
);
export const { selectAll } = adapter.getSelectors();
feature
模块中,创建一个名为selectors.ts
的新文件,定义用于过滤实体的选择器。以下是一个示例代码:import { createSelector } from '@ngrx/store';
import { adapter, State } from './entity.reducer';
export const selectFilter = (state: State) => state.filter;
export const selectFilteredEntities = createSelector(
adapter.getSelectors().selectAll,
selectFilter,
(entities, filter) => {
return entities.filter(entity => entity.name.toLowerCase().includes(filter.toLowerCase()));
}
);
Store
和选择器来获取过滤后的实体。以下是一个示例代码:import { Component } from '@angular/core';
import { Store } from '@ngrx/store';
import { selectFilteredEntities } from './feature/selectors';
@Component({
selector: 'app-my-component',
template: `
- {{ entity.name }}
`,
})
export class MyComponent {
entities$ = this.store.select(selectFilteredEntities);
constructor(private store: Store) {}
}
请注意,上述示例代码中的MyEntity
应该是一个自定义的实体类型,需要根据实际情况进行调整。另外,还可以根据需要添加其他的NGRX操作和选择器。