在Angular NGRX中,要根据id选择ngrx entity中的单个值,你可以使用selectEntityById
选择器。以下是一个示例:
entityAdapter
和一个entityState
:import { createEntityAdapter, EntityState } from '@ngrx/entity';
export interface User {
id: number;
name: string;
}
export const userAdapter = createEntityAdapter();
export interface UserState extends EntityState {
selectedUserId: number | null;
}
export const initialState: UserState = userAdapter.getInitialState({
selectedUserId: null
});
users.reducer.ts
文件,并使用createReducer
来创建一个reducer函数:import { createReducer, on } from '@ngrx/store';
import { EntityState, createEntityAdapter } from '@ngrx/entity';
import { selectUser } from './users.actions';
export interface User {
id: number;
name: string;
}
export const userAdapter = createEntityAdapter();
export interface UserState extends EntityState {
selectedUserId: number | null;
}
export const initialState: UserState = userAdapter.getInitialState({
selectedUserId: null
});
export const userReducer = createReducer(
initialState,
on(selectUser, (state, { id }) => ({
...state,
selectedUserId: id
}))
);
users.selectors.ts
文件,并使用createFeatureSelector
和selectEntityById
来创建一个选择器:import { createSelector, createFeatureSelector } from '@ngrx/store';
import { UserState, userAdapter } from './users.reducer';
export const selectUserState = createFeatureSelector('users');
export const {
selectIds,
selectEntities,
selectAll,
selectTotal,
} = userAdapter.getSelectors(selectUserState);
export const selectSelectedUserId = createSelector(
selectUserState,
(state) => state.selectedUserId
);
export const selectSelectedUser = createSelector(
selectEntities,
selectSelectedUserId,
(entities, selectedUserId) => entities[selectedUserId]
);
selectSelectedUser
选择器来获取所选用户的单个值:import { Component, OnInit } from '@angular/core';
import { Store } from '@ngrx/store';
import { Observable } from 'rxjs';
import { User } from './users.reducer';
import { selectSelectedUser } from './users.selectors';
@Component({
selector: 'app-user-detail',
template: `
User Details
Name: {{ user.name }}
`,
})
export class UserDetailComponent implements OnInit {
user$: Observable;
constructor(private store: Store) {}
ngOnInit() {
this.user$ = this.store.select(selectSelectedUser);
}
}
现在,当你选择一个用户时,UserDetailComponent
组件将根据所选用户的id显示用户的详细信息。
以上就是使用selectEntityById
选择器来根据id选择ngrx entity中的单个值的解决方法。