You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Angular弹窗表单单选框值变更时提交ID数组

实现Angular疫苗状态单选框变更自动提交API方案

关键问题修正与功能实现

先修正当前代码中的字段不匹配、值错误问题,再添加状态变更后的自动提交逻辑:


修改后的HTML代码

<ng-container cdkColumnDef="injected">
    <mat-header-cell *cdkHeaderCellDef class="radioButtonVacXin">
        <p style="width:50px;">
            {{'VacXin.Injected' | translate}}  
        </p>
        <p>
            {{'VacXin.notInjected' | translate}} 
        </p>
        <p>
            {{'VacXin.refuseInjected' | translate}}
        </p>
    </mat-header-cell>
    <mat-cell *cdkCellDef="let item" class="radioButtonVacXin">
        <mat-radio-group class="w-180 radioButtonVacXin" fxLayout="row" 
            [(ngModel)]="item.inject" 
            [ngModelOptions]="{standalone: true}"
            (change)="onVaccineStatusChange(item)">
            <mat-radio-button class="w-60" [value]="1" fxLayoutAlign="center center">
            </mat-radio-button>
            <mat-radio-button class="w-60" [value]="0" fxLayoutAlign="center center">
            </mat-radio-button>
            <mat-radio-button class="w-60" [value]="3" fxLayoutAlign="center center">
            </mat-radio-button>
        </mat-radio-group>
    </mat-cell> 
</ng-container>

HTML修改说明

  • 绑定字段从item.injected改为item.inject,与API返回字段名统一
  • 拒绝接种的单选框值从2修正为需求中的3
  • 添加(change)事件,触发状态变更后的提交逻辑

修改后的TS组件代码

export class AddStaffVacXinComponent implements OnInit {
    item: any = {};
    form: FormGroup;
    formErrors: any;
    isEdit: boolean;
    comboData: any[] = [];
    allManufactory: any[] = [];
    FilterManufactory: any[] = [];
    displayedVacXin = ['injected'];
    params: any = {};
    dataSourceVacXin: MatTableDataSource<any> = new MatTableDataSource<any>([]);
    employeeId: any = {};

    constructor(
        public snackBar: MatSnackBar,
        private translate: TranslatePipe,
        public staffVacXin: StaffVacxinService,
        public dialogRef: MatDialogRef<AddStaffVacXinComponent>,
        @Inject(MAT_DIALOG_DATA) public data: any,
        public dialog: MatDialog,
        private formBuilder: FormBuilder,
    ) {
        if (this.data.item) {
            this.item = Object.assign({}, data.item);
            this.employeeId = this.item.id;
            this.isEdit = true;
        } else {
            this.isEdit = false;
        }
    }

    ngOnInit() {
        this.params = this.employeeId;
        this.staffVacXin.getDetail(this.params).then(res => {
            this.dataSourceVacXin.data = res;
        });
    }

    processResponse(res: boolean) {
        const message = res 
            ? this.translate.transform("Common.Msg.UpdateSuccess") 
            : this.translate.transform("Common.Msg.UpdateError");
        this.snackBar.open(message, "OK", {
            verticalPosition: "top",
            duration: 2000,
        });
        if (res) {
            this.dialogRef.close(res);
        }
    }

    // 疫苗状态变更触发方法
    onVaccineStatusChange(item: any) {
        // 选择1:单独提交当前变更的疫苗项(推荐,减少数据传输)
        this.submitSingleVaccine(item);
        // 选择2:批量提交所有状态对应的疫苗ID数组(适合需要统一提交所有状态的场景)
        // this.submitBatchVaccines();
    }

    // 单个疫苗状态提交
    submitSingleVaccine(item: any) {
        const submitData = {
            vaccinId: item.vaccinId,
            employeeId: this.employeeId,
            inject: item.inject
        };

        this.staffVacXin.updateSingleVaccine(submitData).then(rs => {
            this.processResponse(!!rs);
        }).catch(() => {
            this.processResponse(false);
        });
    }

    // 批量提交所有疫苗状态
    submitBatchVaccines() {
        // 按状态分组收集疫苗ID
        const statusData = {
            employeeId: this.employeeId,
            injectedIds: this.dataSourceVacXin.data.filter(v => v.inject === 1).map(v => v.vaccinId),
            notInjectedIds: this.dataSourceVacXin.data.filter(v => v.inject === 0).map(v => v.vaccinId),
            refuseIds: this.dataSourceVacXin.data.filter(v => v.inject === 3).map(v => v.vaccinId)
        };

        this.staffVacXin.batchUpdateVaccines(statusData).then(rs => {
            this.processResponse(!!rs);
        }).catch(() => {
            this.processResponse(false);
        });
    }

    save() {
        // 保留原有保存逻辑(若需要)
        if (!this.data.isEdit) {
            this.staffVacXin.post(this.item).then(rs => {
                this.processResponse(!!rs);
            });
        } else {
            this.staffVacXin.put(this.item, this.item.id).then(rs => {
                this.processResponse(!!rs);
            });
        }
    }
}

服务层补充方法(StaffVacxinService)

需在服务中添加对应的API调用方法,根据后端接口调整URL和参数格式:

@Injectable({ providedIn: 'root' })
export class StaffVacxinService {
    constructor(private http: HttpClient) {}

    // 单个疫苗状态更新
    updateSingleVaccine(data: any): Promise<any> {
        return this.http.put('/api/staff/vaccine/status', data).toPromise();
    }

    // 批量更新疫苗状态
    batchUpdateVaccines(data: any): Promise<any> {
        return this.http.put('/api/staff/vaccine/batch-status', data).toPromise();
    }

    // 保留原有方法
    getDetail(employeeId: any): Promise<any> {
        return this.http.get(`/api/staff/vaccine/${employeeId}`).toPromise();
    }

    post(item: any): Promise<any> {
        return this.http.post('/api/staff/vaccine', item).toPromise();
    }

    put(item: any, id: any): Promise<any> {
        return this.http.put(`/api/staff/vaccine/${id}`, item).toPromise();
    }
}

核心逻辑说明

  1. 字段统一:确保前端绑定字段与API返回的inject字段一致,避免数据不匹配
  2. 事件触发:通过mat-radio-group的change事件,实时捕获状态变更
  3. 提交方式:提供两种提交方案,可根据后端API设计选择:
    • 单个提交:每次变更只提交当前疫苗的状态,适合接口支持单条更新的场景
    • 批量提交:收集所有疫苗的状态分组后统一提交,适合需要批量同步的场景
  4. 反馈处理:复用原有processResponse方法,统一处理提交后的成功/失败提示

内容的提问来源于stack exchange,提问作者Khánh Dương Đình

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.09 11:35:13