我在 Angular 工作,我有以下情况:
my.service.ts有这个类:
export class MyClass {
MyList: string[] = [];
MyString: string = '';
createString(): void {
this.MyList.forEach(s => {
this.MyString += s + ', ';
});
}
}
而my.component.ts是这样调用的:
myData: MyClass[] = [];
this.myService.getMyData().subscribe(res => {
myData = res;
if (myData.length > 0) {
this.myData.forEach(x => x.createString());
}
});
VS Code 将该createString
函数识别为 的方法MyClass
,但我仍然收到错误消息:
错误类型错误:x.createString 不是函数
有什么解释吗?
编辑:数据来自后端,后端模型没有这个方法。也许这就是问题所在?
来自服务器的对象只是一个简单的对象,而不是类的实例MyClass
。您可以创建实例MyClass
并将值从服务器对象分配给类的实例:
this.myService.getMyData().subscribe(res => {
myData = res.map(o => Object.assign(new MyClass(), o));
if (myData.length > 0) {
this.myData.forEach(x => x.createString());
}
});
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句