According to the NGXS documentation, the following is all valid code:
import { Select } from '@ngxs/store';
import { ZooState, ZooStateModel } from './zoo.state';
@Component({ ... })
export class ZooComponent {
// Reads the name of the state from the state class
@Select(ZooState) animals$: Observable<string[]>;
// Uses the pandas memoized selector to only return pandas
@Select(ZooState.pandas) pandas$: Observable<string[]>;
// Also accepts a function like our select method
@Select(state => state.zoo.animals) animals$: Observable<string[]>;
// Reads the name of the state from the parameter
@Select() zoo$: Observable<ZooStateModel>;
}
My question is specifically about that third @Select
. How, exactly, does the decorator and/or framework know which state should be used in the lambda? There is nothing obvious here to say "this component uses ZooState as its state object," so how can the correct state slice to look at be determined?
For the record, this pattern does seem to work just fine - I'm just a bit stumped as to HOW.
CodePudding user response:
When using the NGXS @Select
decorator with a function referring to the target state, the state
arg in this case represents the whole state object that contains all the registerd states by their names that provided within @State
decorator (such as: @State<ZooStateModel>({ name: 'zoo' })
)
For example, if you have 3 states, defined as: zoo
, app
, and foo
, and registed within the store, then the type of the state
arg will be like the following:
@Select((state: { zoo: ZooStateModel; app: AppStateModel; foo: FooStateModel }) => state.zoo.animals)
animals$: Observable<string[]>;