I'm attempting to encapsulate my ngrx state in a shared service class to abstract the implementation details away from my components.
Example service class that is registered in my app.module.ts providers
@Injectable()
export class PatientService {
state: Observable<PatientState>;
constructor(
private store: Store<AppState>,
) {
this.state = store.select<PatientState>('patients');
}
}
I have verified my actions, reducer and effects are working as expected, however, when I subscribe to the service state in a component, it returns undefined
.
Example component subscription using the shared service:
@Component({
...
})
export class DashboardComponent implements OnInit {
constructor(
private patientService: PatientService,
) {}
ngOnInit(): void {
// dispatches action to load patient from API
this.patientService.loadPatient();
this.patientService.state.subscribe(patientState => {
console.log('patientState', patientState);
// Does not work. Logs undefined.
});
}
}
If I subscribe directly to the store, it works as expected.
Example:
@Component({
...
})
export class DashboardComponent implements OnInit {
constructor(
private patientActions: PatientActions,
private store: Store<AppState>,
) {}
ngOnInit(): void {
this.store.dispatch(this.patientActions.loadPatient());
this.store.select<PatientState>('patients').subscribe(patientState => {
console.log('patientState', patientState);
// Works as expected.
});
}
}
What am I doing wrong?
state === undefined
always. It was very confused for me, but finally I've found corresponding reducer is not implemented magic code:default: return state;
. Hope it'll help to somebody – Mergasov