如何在TypeScript中访问BehaviorSubject传递的对象属性
问题:BehaviorSubject传递的值在TypeScript代码中无法访问属性,但HTML中async管道可正常显示
我尝试将组件「Modal-accion-reforma」的值传递给「entidad-tablas-buscador」,使用BehaviorSubject实现数据共享。目前HTML中通过async管道能正常渲染_tipoEnumCod等属性,但在TypeScript代码里无法直接访问这些属性。
相关代码
服务「accion-reforma」
export interface tipoInit { _tipoEnumCod: string, _numNorma: number, _tipoNormaId: string, _listEntidades: [] }; const inittipoInit: tipoInit = { _tipoEnumCod: "CREA", _numNorma: 1, _tipoNormaId: "a", _listEntidades: [] } private tipo$ = new BehaviorSubject<tipoInit>(inittipoInit); get selectedtipo$():Observable<tipoInit>{ return this.tipo$.asObservable(); } setTipo(tipo:tipoInit):void{ this.tipo$.next(tipo) }
发送组件「Modal-accion-reforma」
tipos: tipoInit[] =[]; selection!: tipoInit; constructor( private accionReformaService: AccionReformaService, public dialogRef: MatDialogRef<ModalAccionReformaComponent>, @Inject(MAT_DIALOG_DATA) public data: DialogData, ) {} ngOnInit(): void { this.accionReformaService.selectedtipo$.subscribe((tipoint: tipoInit) => this.selection = tipoint) } Ir_accion_reforma(tipoEnumCod:string, numNorma:any, tipoNormaId:any ){ this.selection._tipoEnumCod = tipoEnumCod this.selection._numNorma = numNorma this.selection._tipoNormaId = tipoNormaId this.accionReformaService.setTipo(this.selection); }
接收组件「entidad-tablas-buscador」
selectedtipo$ = this.accionReformaService.selectedtipo$; constructor(private accionReformaService: AccionReformaService, private _formBuilder: FormBuilder, private entidadService: EntidadService) {} ngOnInit(): void { console.log("AHORA VEREMOS: "+ this.selectedtipo$) /* 无法访问_tipoEnumCod、_numNorma等属性 */ }
接收组件HTML
<label fxFlex="30%">Nivel de la entidad: {{(selectedtipo$ | async)?._tipoEnumCod}}</label>
解决方案
核心原因是selectedtipo$是Observable类型,并非直接的tipoInit对象,必须通过订阅(subscribe)才能获取流中的实际值。
1. 订阅Observable获取属性
在接收组件的ngOnInit中手动订阅,即可访问对象属性:
ngOnInit(): void { this.selectedtipo$.subscribe(tipo => { console.log("TipoEnumCod:", tipo._tipoEnumCod); console.log("NumNorma:", tipo._numNorma); console.log("TipoNormaId:", tipo._tipoNormaId); // 在此处可正常操作所有属性 }); }
2. (可选)保存当前值到组件变量
如果需要在组件其他方法中复用该值,可声明变量存储:
currentTipo!: tipoInit; ngOnInit(): void { this.selectedtipo$.subscribe(tipo => { this.currentTipo = tipo; // 后续可通过this.currentTipo._tipoEnumCod访问属性 }); }
3. 优化发送组件的对象更新逻辑
直接修改原对象可能引发引用问题,建议创建新对象发送:
Ir_accion_reforma(tipoEnumCod:string, numNorma:any, tipoNormaId:any ){ const newSelection = { ...this.selection, _tipoEnumCod: tipoEnumCod, _numNorma: numNorma, _tipoNormaId: tipoNormaId }; this.accionReformaService.setTipo(newSelection); }
为什么HTML能正常显示?
async管道在内部自动完成了订阅-取值-自动取消订阅的流程,帮你处理了Observable的异步特性,因此能直接渲染对象属性;而TypeScript代码中必须手动订阅才能获取异步流中的实际数据。
内容的提问来源于stack exchange,提问作者Mr Usher
相关产品推荐
相关产品推荐

