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

如何在Angular响应式表单中使用get/set方法设值并解决调用报错

问题原因

JavaScript/TypeScript 中的 set 语法定义的是赋值器属性,不是普通方法,不能通过括号()调用,必须通过=赋值的方式触发set逻辑。你现在用this.apiCodesFile(file)的写法,自然会抛出「不是函数」的类型错误。

解决方案

修改onFileSelect方法里的赋值逻辑,用赋值语法触发setter即可:

set apiCodesFile (val) {
    this.form.get('apiCodesFile').setValue(val);
}

public onFileSelect(event) {
    if (event.target.files.length > 0) {
        this.isFileSelected = true;
        const file = event.target.files[0];
        // 把括号调用改成直接赋值即可触发setter
        this.apiCodesFile = file;
    } else {
        this.isFileSelected = false;
    }
}

可选方案:定义普通赋值方法

如果你偏好函数调用的写法,不需要用set关键字,直接声明普通方法即可:

// 去掉set关键字,定义为普通方法
public setApiCodesFile (val) {
    this.form.get('apiCodesFile').setValue(val);
}

public onFileSelect(event) {
    if (event.target.files.length > 0) {
        this.isFileSelected = true;
        const file = event.target.files[0];
        // 方法调用就不会报错
        this.setApiCodesFile(file);
    } else {
        this.isFileSelected = false;
    }
}

内容的提问来源于stack exchange,提问作者RoshiDil

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.02 01:18:01