我正在尝试将我的ngrx状态封装在共享服务类中,以从我的组件中抽象出实现细节.
在app.module.ts提供程序中注册的示例服务类
@Injectable() export class PatientService { state: Observable<PatientState>; constructor( private store: Store<AppState>,) { this.state = store.select<PatientState>('patients'); } }
我已经验证了我的操作,reducer和effect正在按预期工作,但是,当我订阅组件中的服务状态时,它返回undefined.
使用共享服务的示例组件订阅:
@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. }); } }
如果我直接订阅商店,它会按预期工作.
例:
@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. }); } }
我究竟做错了什么?
我已经实现了类似的用例.你的尝试很好,我用这种方式工作:
@Injectable() export class PatientService { // Define Observable patientState$: Observable<PatientState>; constructor(private store: Store<AppState>) { // Get data from the store this.patientState$= store.select<PatientState>('patients'); } getState(): PatientState { // subscribe to it so i don't have to deal with observables in components let patientState: PatientState = null; this.patientState$.subscribe(ps => patientState = ps); return patientState; } }
@Component({ ... }) export class DashboardComponent implements OnInit { patientState = new PatientState; constructor( private patientService: PatientService,) {} ngOnInit(): void { // Simply get the Object from the store without dealing with observables this.patientState = this.patientService.getState(); } }
我在observables的末尾使用$所以我知道每次触摸变量时它是否是Observable,这样我就不会感到困惑.