Angular中调用Service内Attachment对象clean方法时出现类型错误
嘿,这个问题其实是Angular新手很容易踩的一个坑,我来给你掰明白!
你遇到的attachment.clean is not a function错误,核心原因是:this.attachments数组里的元素并不是Attachment类的实例,只是结构和它相似的普通JavaScript对象。
你在populateAttachments里通过服务获取的数据(比如HTTP请求返回的JSON),本质上是浏览器把JSON字符串解析成的普通对象——它们有type、reasonPicked这些属性,但并没有继承Attachment类的方法(比如clean)。而你手动用new Attachment(...)创建的实例,是真正的类对象,所以能正常调用clean方法。
另外顺便提一句,你的Attachment构造函数里有个小bug:第三个参数是option_picked,但你赋值的时候写的是this.optionPicked = reason_picked,这会导致optionPicked的值和reasonPicked完全一样,记得改成this.optionPicked = option_picked哦!
要解决这个问题,你需要把从服务拿到的普通对象转换成Attachment类的实例,下面给你两种常用的方式:
方式1:直接在数据获取后转换实例
修改populateAttachments方法,当你拿到数据后,用map把每个普通对象转成Attachment实例:
populateAttachments() { // 假设你是通过HttpClient获取数据 this.http.get<any[]>('你的API地址').subscribe(data => { this.attachments = data.map(item => new Attachment( item.type, item.reasonPicked, item.optionPicked, // 这里对应构造函数的第三个参数,注意顺序 item.documentName, item.document ) ); }); }
方式2:用静态方法封装转换逻辑(更优雅)
给Attachment类添加一个静态方法,专门用来从JSON对象创建实例,这样代码更易维护:
export class Attachment { type: string; reasonPicked: number; optionPicked: number; documentName: string; document: string; constructor(type: string, reason_picked: number, option_picked: number, documentName: string, document: string) { this.type = type; this.reasonPicked = reason_picked; this.optionPicked = option_picked; // 修复之前的bug this.documentName = documentName; this.document = document; } // 新增静态方法,从JSON对象创建实例 static fromJson(json: Partial<Attachment>): Attachment { // 给默认值避免属性缺失导致的错误 return new Attachment( json.type ?? '', json.reasonPicked ?? 0, json.optionPicked ?? 0, json.documentName ?? '', json.document ?? '' ); } public clean() { this.reasonPicked = 0; // ... 其他清理逻辑 } }
然后在populateAttachments里这样用:
populateAttachments() { this.http.get<any[]>('你的API地址').subscribe(data => { this.attachments = data.map(item => Attachment.fromJson(item)); }); }
这样处理后,this.attachments里的每个元素都是真正的Attachment实例,调用clean方法就不会报错啦!
内容的提问来源于stack exchange,提问作者Jester Shoeman

