I am using the property key 'auth' to scope the reducer in the StoreModule.forRoot setting so I can add other reducers in the future.
But this seems to conflict with my selectors.
./app.module.ts
@NgModule({
declarations: [
AppComponent,
],
imports: [
StoreModule.forRoot({
// here is a 'auth' key
auth: authStateReducer,
}),
EffectsModule.forRoot([AuthEffects]),
//...
./auth.state.ts
export interface AuthState {
token: string;
}
./auth.selectors.ts
export const selectToken = (state: AuthState) => state.token;
./auth.guard.ts
@Injectable()
export class AuthGuard implements CanActivate {
constructor(
private store: Store<AuthState>,
) {}
this.store.select(selectToken)
.subscribe((token) => {
console.log(token) // logs undefined
});
}
When I adjust the store to private store: Store<{ auth: AuthState }>,
, and then the selector to: export const selectToken = ({ auth: state }) => state.token;
it does work.
However, It seems strange that my selector has knowledge of some setting in app.module.ts.
Is there another way?
CodePudding user response:
First select the auth
, then you can select the state from the auth
slice.
To select the top-level state, use createFeatureSelector
.
const selectAuthState = createFeatureSelector<AuthState>('auth');
export const selectToken = createSelector(selectAuthState, (state) => state.token);