Angular+NgRx开发:如何在Feature Module中获取状态?
Hey there! Let's break down your NgRx questions clearly, step by step.
fromStore First: Properly Fetching Feature State
Your current code this.store.select(state => state.todos.data) does work—it directly grabs the data slice from the todos feature state attached to the root store. But this isn't the most maintainable approach. NgRx encourages using feature selectors to make your code modular and resilient to changes.
Here's how to do it the "NgRx way":
- Define feature-specific selectors in your
todosfeature store files (e.g.,todos.selectors.ts):import { createFeatureSelector, createSelector } from '@ngrx/store'; import { TodosState } from './todos.state'; // Grab the entire TodosState from the root store export const selectTodosState = createFeatureSelector<TodosState>('todos'); // Drill down to the `data` slice of the TodosState export const selectTodosData = createSelector( selectTodosState, (state: TodosState) => state.data ); - Use these selectors in your component:
import { selectTodosData } from './store/todos.selectors'; // ... this.todos$ = this.store.select(selectTodosData);
This way, if you ever rename the feature key (the 'todos' string) or adjust the state structure, you only need to update the selectors—not every component that uses the state.
What Exactly is fromStore?
fromStore is just a custom import alias developers use to clean up imports for feature store code. Instead of writing long import paths for selectors, actions, or reducers every time, you can bundle them into a single alias.
For example, if you export all your store-related code (selectors, actions, reducers) from a single file like todos.store.ts or an index.ts in your store folder, you can import it like this:
import * as fromStore from './store/todos.store';
Then you can reference selectors/actions using the alias:
this.todos$ = this.store.select(fromStore.selectTodosData);
It's purely a convenience to keep your code clean and readable—there's no special NgRx magic behind the fromStore name itself; you could name it fromTodosStore or anything else if you wanted.
Why Your Original Code Works (But Should Be Improved)
Your initial code works because NgRx attaches all feature states to the root store object using their feature key as the property name. But hardcoding state.todos.data makes your code fragile:
- If you change the feature key (e.g., from
'todos'to'userTodos'), you'll have to find and replace every instance ofstate.todos - If the
TodosStatestructure changes (e.g., movingdataunder acontentproperty), you'll have to update all direct state accesses
Using feature selectors and the fromStore alias fixes these issues and aligns with NgRx best practices.
内容的提问来源于stack exchange,提问作者Maks K

