Angular:子组件如何随基组件candidate变量更新同步数据
解决方案
方法1:基组件暴露Observable,子组件订阅同步
在基组件profile.component.ts中,将候选者状态的Observable设为protected(仅子类可访问),同时保留原有订阅逻辑更新this.candidate:
// profile.component.ts import { Subscription } from 'rxjs'; // 假设已导入对应的store和selectCandidateState,以及Candidate类型 protected candidate$ = this.store.select(selectCandidateState); private candidateSub!: Subscription; protected candidate: CandidateType | undefined; ngOnInit() { this.candidateSub = this.candidate$.subscribe((candidateState) => { this.candidate = candidateState; }); } ngOnDestroy() { this.candidateSub?.unsubscribe(); }
子组件SkillsComponent中订阅该Observable,同步更新candidateSkills:
// skills.component.ts import { Subscription } from 'rxjs'; private candidateSkillsSub!: Subscription; public candidateSkills: SkillType[] | undefined; ngOnInit() { super.ngOnInit(); // 必须调用基组件初始化逻辑 this.candidateSkillsSub = this.candidate$.subscribe(candidate => { this.candidateSkills = candidate?.skills; }); } ngOnDestroy() { super.ngOnDestroy(); this.candidateSkillsSub?.unsubscribe(); }
方法2:基组件用Setter+钩子方法触发子组件更新
在基组件中给candidate设置Setter,值变更时调用protected钩子函数,子组件重写钩子实现同步:
// profile.component.ts private _candidate: CandidateType | undefined; protected get candidate(): CandidateType | undefined { return this._candidate; } protected set candidate(value: CandidateType | undefined) { this._candidate = value; this.onCandidateUpdated(value); // 触发钩子 } // 空钩子方法,供子类重写 protected onCandidateUpdated(candidate: CandidateType | undefined): void {} ngOnInit() { this.candidateSub = this.store.select(selectCandidateState).subscribe((candidateState) => { this.candidate = candidateState; // 赋值触发Setter }); }
子组件重写钩子函数,同步candidateSkills:
// skills.component.ts public candidateSkills: SkillType[] | undefined; ngOnInit() { super.ngOnInit(); // 初始化时同步一次 this.candidateSkills = this.candidate?.skills; } protected override onCandidateUpdated(candidate: CandidateType | undefined): void { this.candidateSkills = candidate?.skills; }
内容的提问来源于stack exchange,提问作者ABGR
相关产品推荐
相关产品推荐

