angular – ngrx状态未定义
发布时间:2020-12-17 07:22:19 所属栏目:安全 来源:网络整理
导读:我正在尝试将我的ngrx状态封装在共享服务类中,以从我的组件中抽象出实现细节. 在app.module.ts提供程序中注册的示例服务类 @Injectable()export class PatientService { state: ObservablePatientState; constructor( private store: StoreAppState,) { this
我正在尝试将我的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,这样我就不会感到困惑. (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |
推荐文章
站长推荐
热点阅读