如何通过子组件输入更新Angular Service中的数组值?
从子组件更新Angular服务中的数组值
1. 完善FeatureService,添加数组更新方法
首先修正原服务的语法错误(printFeatureArray需放在类内部),并新增用于修改数组元素的方法,通过Feature的ID定位目标项进行更新:
export class FeatureService { private myFeatures: MyFeature[] = [ new Feature(1, '1st Empty String'), new Feature(2, '2nd Empty String'), new Feature(3, '3rd Empty String'), ]; getFeatures() { return this.myFeatures.slice(); } printFeatureArray() { console.log(this.myFeatures); } // 新增:根据ID更新Feature的输入值 updateFeatureValue(featureId: number, newValue: string): void { const targetFeature = this.myFeatures.find(feature => feature.id === featureId); if (targetFeature) { targetFeature.inputValue = newValue; // 假设MyFeature类包含inputValue属性 } } }
2. 修正中间组件的代码问题
原组件存在依赖注入和变量引用错误,修正后如下:
component.ts
export class FeatureListComponent { myFeatures: MyFeature[] | undefined; constructor(private featureService: FeatureService) {} // 注入正确的服务 ngOnInit() { this.myFeatures = this.featureService.getFeatures(); // 调用服务的获取方法 } }
component.html
循环时需将当前遍历项传递给子组件:
<div class="list" *ngFor="let myFeature of myFeatures; let i = index" > <app-my-item [docFeature]="myFeature"></app-my-item> </div>
3. 实现子组件的更新逻辑
子组件需接收父组件传递的Feature实例,并注入服务调用更新方法:
my-item.component.ts
import { Input } from '@angular/core'; import { FeatureService } from '../feature.service'; export class MyItemComponent { @Input() docFeature: MyFeature | undefined; // 接收父组件传递的Feature constructor(private featureService: FeatureService) {} // 注入服务 getValue(value: string) { if (this.docFeature) { this.featureService.updateFeatureValue(this.docFeature.id, value); // 可选:调用打印方法查看更新后的数组 this.featureService.printFeatureArray(); } } }
my-item.component.html
改用属性绑定优化placeholder写法:
<input #inputTag (keyup)="getValue(inputTag.value)" [ngClass]="addClassTemplate()" (click)="onSelected()" type="text" [placeholder]="docFeature?.inputValue" />
可选:实现响应式更新(自动刷新视图)
如果希望组件能自动感知服务中数组的变化,可将服务改为基于Observable实现:
服务侧修改
import { BehaviorSubject } from 'rxjs'; export class FeatureService { private myFeatures: MyFeature[] = [ new Feature(1, '1st Empty String'), new Feature(2, '2nd Empty String'), new Feature(3, '3rd Empty String'), ]; private myFeaturesSubject = new BehaviorSubject<MyFeature[]>(this.myFeatures); myFeatures$ = this.myFeaturesSubject.asObservable(); // 对外暴露可观察对象 printFeatureArray() { console.log(this.myFeatures); } updateFeatureValue(featureId: number, newValue: string): void { const targetFeature = this.myFeatures.find(feature => feature.id === featureId); if (targetFeature) { targetFeature.inputValue = newValue; this.myFeaturesSubject.next([...this.myFeatures]); // 发送新数组引用触发视图更新 } } }
中间组件订阅更新
ngOnInit() { this.featureService.myFeatures$.subscribe(features => { this.myFeatures = features; }); }
内容的提问来源于stack exchange,提问作者Kevin
相关产品推荐
相关产品推荐

