Angular父子组件数据共享异常:子组件传值至父组件时参数为null
嘿,兄弟,我一眼就瞅出问题出在哪儿了!你在父组件模板里绑定子组件的emitEvent事件时,犯了一个典型的小错误——你没有接收子组件传过来的新值,反而把父组件自己还没更新的旧值传进了处理方法里。
具体问题分析
看你父组件的HTML代码:
<jhi-saison-dashboard-top-header [saisonSelectionnee]="saisonSelectionnee" (emitEvent)="evenementDeTopheader(saisonSelectionnee!)"> </jhi-saison-dashboard-top-header>
这里你调用evenementDeTopheader时传的是父组件自己的saisonSelectionnee!,但这个值在子组件触发emitEvent的瞬间还没被更新(因为父组件的evenementDeTopheader方法正是要用来更新它的)。如果之前这个值是null,那你传进去的自然就是null,完全忽略了子组件通过emitEvent发过来的真实有效对象。
修复步骤
1. 修正父组件的事件绑定
把两个子组件的emitEvent绑定改成接收Angular事件对象$event——这个$event就是子组件通过emitEvent.next()传过来的ISaison对象:
<div> <!-- 包含季节列表和管理按钮的栏位--> <jhi-saison-dashboard-top-header [saisonSelectionnee]="saisonSelectionnee" (emitEvent)="evenementDeTopheader($event)"> </jhi-saison-dashboard-top-header> <!-- 授权日/月参数管理区域 --> <jhi-saison-dashboard-option [saisonSelectionnee]="saisonSelectionnee" (emitEvent)="evenementDeOption($event)"> </jhi-saison-dashboard-option> </div>
这样父组件的evenementDeTopheader和evenementDeOption方法就能接收到子组件传过来的最新ISaison对象,赋值后就能正常同步给另一个子组件了。
2. (可选)优化子组件代码
你的子组件里有个可以优化的小细节:changementSaisonDansListe方法里先delete this.saisonSelectionnee完全没必要,而且错误处理的写法也有问题(你把错误回调写在了subscribe外面)。可以改成更简洁健壮的版本:
changementSaisonDansListe(): void { if (this.saisonIdSelectionnee) { this.saisonService.find(this.saisonIdSelectionnee).subscribe({ next: (res) => { // 用空合并运算符处理返回值为空的情况 this.saisonSelectionnee = res.body ?? undefined; this.emitEvent.next(this.saisonSelectionnee); }, error: () => { // 错误时也要通知父组件,避免状态不一致 this.saisonSelectionnee = undefined; this.emitEvent.next(this.saisonSelectionnee); // 这里可以加用户提示,比如alert('获取季节信息失败') } }); } }
验证效果
改完之后,当子组件切换季节并触发emitEvent时,父组件会接收到子组件传过来的有效ISaison对象,更新自己的saisonSelectionnee,然后这个值会通过@Input同步给另一个子组件,完美实现两个子组件的数据共享~
内容的提问来源于stack exchange,提问作者Broshet

