问题描述:在使用Angular 14和NGRX时,选择器无法正确工作。
import { createSelector } from '@ngrx/store';
import { Component } from '@angular/core';
import { Observable } from 'rxjs/Observable';
import { Store, createSelector } from '@ngrx/store';
import { AppState } from '../app.state';
import { getSelectedUser } from '../user.selectors';
import { User } from '../user';
@Component({
selector: 'app-selected-user',
templateUrl: './selected-user.component.html',
styleUrls: ['./selected-user.component.css']
})
export class SelectedUserComponent {
public selectedUser$: Observable;
constructor(private store: Store) {
this.selectedUser$ = this.store.select(getSelectedUser);
}
}
of
方法将其转换为 Observable。例如:import { createFeatureSelector, createSelector } from '@ngrx/store';
import { User } from './user';
export interface UserState {
users: User[];
selectedUserId: number;
}
export const getUserState = createFeatureSelector('users');
export const getUsers = createSelector(
getUserState,
state => state.users
);
export const getSelectedUserId = createSelector(
getUserState,
state => state.selectedUserId
);
export const getSelectedUser = createSelector(
getUsers,
getSelectedUserId,
(users, selectedUserId) => {
if (users && selectedUserId) {
return users.find(user => user.id === selectedUserId);
} else {
return null;
}
}
);
这些步骤应该有助于解决您在使用 Angular 14 和 NGRX 时遇到的选择器问题。