Selecting data from an Ngrx store has always been achieved by using selectors. As Ngrx has developed over the last couple of years, selectors have become easier and easier to use.
interface Customer { id: number; name: string; }
interface AppState { customers: Customer[] }
export const selectCustomers = (state: AppState) => state.customers;
The above selectCustomers selector conveniently returns Customers from the store.
How can we select a single customer entity from the store by its id?
To do this is nice and simple in Ngrx 12+; we can use a factory selector.
import { createSelector } from '@ngrx/store';
interface Customer { id: number; name: string; }
interface AppState { customers: Customer[] }
export const selectCustomers = (state: AppState) => state.customers;
// selector with param
export const selectCustomerById = (customerId: number) =>
createSelector(
selectCustomers,
(customers: Customers[]) =>
customers.find(c => c.id === customerId)
)
We can then get a customer with the id of 123 from the store; by passing a value for the customerId into our selector:
this.store.select(selectCustomerById(123));
Hope this helps you all out as the older method of using props is now deprecated in Ngrx 12+. (https://github.com/ngrx/platform/issues/2980)
I also have a YouTube channel called Coffee Music & Coding which you may find useful for Angular and Ngrx tutorials.
Top comments (2)
thanks
Thanks! Simple and easy